Add multiple window.onload events Add multiple window.onload events asp.net asp.net

Add multiple window.onload events


Most of the "solutions" suggested are Microsoft-specific, or require bloated libraries. Here's one good way. This works with W3C-compliant browsers and with Microsoft IE.

if (window.addEventListener) // W3C standard{  window.addEventListener('load', myFunction, false); // NB **not** 'onload'} else if (window.attachEvent) // Microsoft{  window.attachEvent('onload', myFunction);}


There still is an ugly solution (which is far inferior to using a framework or addEventListener/attachEvent) that is to save the current onload event:

function addOnLoad(fn){    var old = window.onload;   window.onload = function()   {       old();       fn();   };}addOnLoad(function(){   // your code here});addOnLoad(function(){   // your code here});addOnLoad(function(){   // your code here});

Note that frameworks like jQuery will provide a way to execute code when the DOM is ready and not when the page loads.

DOM being ready means that your HTML has loaded but not external components like images or stylesheets, allowing you to be called long before the load event fires.


I had a similar problem today so I solved it having an index.js with the following:

window.onloadFuncs = [];window.onload = function(){ for(var i in this.onloadFuncs) {  this.onloadFuncs[i](); }}

and in additional js files that i want to attach the onload event I just have to do this:

window.onloadFuncs.push(function(){ // code here});

I normally use jQuery though, but this time I was restricted to pure js wich forced to use my mind for a while!