window.onload = function(){}; works, but as you can see , you can specify only 1 listener .
I would say that a better / newer way to do this is to use a framework or simply use a simple implementation of the native addEventListener and attachEvent (for IE), which allows you to remove listeners for events as well.
Here's a cross-browser implementation:
// Cross-browser implementation of element.addEventListener() function listen(evnt, elem, func) { if (elem.addEventListener) // W3C DOM elem.addEventListener(evnt,func,false); else if (elem.attachEvent) { // IE DOM var r = elem.attachEvent("on"+evnt, func); return r; } else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.'); } // Use: listen("event name", elem, func);
For the case of window.onload, use: listen("load", window, function() { });
EDIT . I would like to expand my answer by adding valuable information that others have pointed out.
These are DOMContentLoaded (Mozilla, Opera, and webkit night hours are currently supported) and onreadystatechange events (for IE) that can be applied to the document object to understand when a document is available for management (without waiting for all images / stylesheets to load etc.).
There are many "hacker" implementations to support cross-browsers, so I highly recommend using a framework for this feature.
Luca Matteis Feb 17 '09 at 23:15 2009-02-17 23:15
source share