Add load event
When a web page has finished loading the onload event is triggered. This is attached to the window object. You could and should use it to run a function when the page loads:
window.onload = functionName;
This works fine, but what if you want to execute more than one function once the page has loaded? You can only call window.onload once. In fact, if you tried to use it twice, only the latter call would actually execute. Fortunately, there are at least a couple of solutions: an anonymous function or Simon Willison's addLoadEvent function.
Anonymous Function
window.onload = function() {
function1();
function2();
etc();
}
addLoadEvent Function
The function:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
Adding onload calls:
addLoadEvent(function1); addLoadEvent(function2); addLoadEvent(etc);
I'll leave the explanation of the code to the author:
The
addLoadEventfunction takes as an argument another function which should be executed once the page has loaded. Unlike assigning directly towindow.onload, the function adds the event in such a way that any previously added onload functions will be executed first.The way this works is relatively simple: if
window.onloadhas not already been assigned a function, the function passed toaddLoadEventis simply assigned towindow.onload. Ifwindow.onloadhas already been set, a brand new function is created which first calls the original onload handler, then calls the new handler afterwards.
addLoadEventhas one very important property: it will work even if something has previously been assigned to window.onload without usingaddLoadEventitself. This makes it ideal for use in scripts that may be executing along side other scripts that have already been registered to execute once the page has loaded.
Further reading and sources
- Simon Willison's Executing JavaScript on page load article