JavaScript Onload Function

Written something you are proud of, post it here.
Post Reply
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

JavaScript Onload Function

Post 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.
Image
Post Reply