Page 1 of 1

JavaScript Onload Function

Posted: Mon May 30, 2011 4:25 pm
by jacek
This function will add a function that you give it to a list to be executed when the DOM is done loading.
// adds a function to the windows load event.
function add_onload (func) {
	if (typeof window.addEventListener !== 'undefined') {
		window.addEventListener('load', func, false);
	} else if (typeof window.attachEvent !== 'undefined') {
		window.attachEvent('onload', func);
	} else {
		if (typeof window.onload !== 'function') {
			window.onload = func;
		} else {
			var old_onload = window.onload;
			
			window.onload = function () {
				old_onload();
				func();
			}
		}
	}
}
It will work in all browsers, and has a fallback to the old window.onload method in case any of the correct methods are not available.

example useage...
add_onload(function () {
    alert('test 1');
});

add_onload(function () {
    alert('test 2');
});
Will show the two alerts once the HTML for the page has finished loading.