Saturday, March 22, 2008

A better alternative to window.onload

This code can be used as a better alternative to window.onload. We use main as the function from where the execution begins. We also have a __app_started varible which tracks if main has been called so that it is not called more than once. Basically by this technique main gets called the moment body has been completed. If you use window.onload it waits till all the images and CSS have been loaded and in most case that can really be a while.
var __app_started = false;
if(document.addEventListener) document.addEventListener("DOMContentLoaded", main, false);
document.write("<scr" + "ipt id=__ie_onload defer src=javascript:void(0)><\/scri" + "pt>");
var script = document.getElementById("__ie" + "_onlo" + "ad");
script.onreadystatechange = function()
if(this.readyState == "complete") main();

window.onload = main; // If all else fails

function main()
if(__app_started) return; // We don't want to call main more than once.

//App logic goes here

__app_started = true;

1 comment:

Anonymous said...

Nice,still works, thanks a lot.