Home > JavaScript > Running JavaScript when the page finishes loading

Running JavaScript when the page finishes loading

I know what you’re thinking. window.onload and <body onload> already let you run javascript when the page loads. Why do I need something more? The answer is that the standard onload only runs when the entire page and its dependencies are finished loading. This means that if you have multiple images (such as tracking tags) or scripts or a large swf, the onloaded code will only run once all of those pieces load. The point of the following is to run some JavaScript once the page itself has loaded and been parsed. This allows you to do things like set the background color, add additional elements, or start loading other dependencies while the rest of the page’s depdencies are loading. This is particularly useful if you need to do something on a page while a large swf is loading.

The following is a combination of several posts on Dean Edwards’ blog as well as an onload handler for those browsers that don’t support this kind of solution that I found elsewhere. This may not work in Opera, I am not sure. According to the second post Opera supports DOMContentLoaded but I don’t know if this code will catch Opera properly.

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;
  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;
 
  //CODE TO RUN GOES HERE
}
 
// for Mozilla browsers
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
} else
// for Safari
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      clearInterval(_timer);
      init(); // call the onload handler
    }
  }, 10);
} else
//for those other poor souls
{
  function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
      window.onload = func;
    } else {
      window.onload = function() {
        oldonload();
        func();
      }
    }
  }
  addLoadEvent(init);
}
// for Internet Explorer (using conditional comments)
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id='__ie_onload' src='javascript:void(0)'></script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
  if (this.readyState == "complete") {
    init(); // call the onload handler
  }
};
/*@end @*/

UPDATE: fixed the code above. WordPress was screwing up the last bit due to its insistence on changing the preformatted HTML in the code.

Categories: JavaScript Tags: ,