Sometimes when writing JavaScript I need to have something run as soon as the page has finished loading. This is usually done by placing a call to the function in the body’s onload attribute like:

<body onload="myFunc()">

But this is not always possible. For example by the time you get to your logic that decides it necessary to call a function onload, the header may have already been displayed by a cfinclude or by your framework.

You could use JavaScript to set the onload event, like

window.onload = myFunc;

But what if there was already something in the onload attribute of the body tag? The above code will reset whatever was there. But here is a nice snippet of code that will add functions to the onload event. I can’t take credit for it, and I don’t remember exactly where I found it but its been quite useful to me. It works in all the popular browsers.

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

Then you can add as many functions as you want to be called when the page loads. Note you do not use parenthesis when specifying the function names – you aren’t calling then, just referencing them.

addLoadEvent(myFunc);
addLoadEvent(myFunc2);
addLoadEvent(yetAnotherFunction);

4 Comments

  1. Jake Churchill says:

    Nice!

  2. Boyan Kostadinov says:

    Or you can always use the on load facilities provided with Prototype.js or jQuery and those would take care of that problem out of the box.

  3. aniyah says:

    Nice article thanks for sharing!

  4. jh says:

    thx!