.

Friday, June 09, 2006

window.onload is soooo '90s! #

Highly insipred from Brothercake's domfunction.

I am working on a client-heavy ajax application and the more responsive I manage to make it; the better. Making the application load as fast as possible is a must-have goal for me.

As you know, when DOM content loads and becomes readily available you can execute additional initialization scripts to lazy-initialize and organize the page.

In 90's this was mainly done by attaching an onload eventhandler to the window. Like

window.onload=function()
{
//initialization logic comes here.
}

This, however, means that our function will not only wait the DOM content to load, but it also will wait the entire body to fully load (including images, flash objects, vendor-specific custom components, HTC components, applets... and the like)

If you have a lot of such content, your web application will seem to load really really sloooooow.

Using window.onload is so '90s!

Let us write a quickLoad method, which executes as soon as the DOM is ready, without requiring a truckload of additional objects to load. This way, our web application will load and respond much faster.

First prerequisites:
var DomLoadController=
{
index:0,
sanityLimit:50,
interval:-1,
retryMilli:256
}

function executeWhenReady(fnDelegate)
{
DomLoadController.index++;

if(typeof document.getElementsByTagName != 'undefined' &&
(document.getElementsByTagName('body')[0] != null ||
document.body != null))
{
fnDelegate();
clearInterval(DomLoadController.interval);
}

if(DomLoadController.index >= DomLoadController.sanityLimit)
{
clearInterval(DomLoadController.interval);

//if you exceed the sanity limit, try to load the
//function using traditional mehtods,
//attaching an EventHandler to window load.

//Note that _.chain is a utility method of sardalya
_.chain(window,"load",fnDelegate);

}
}

function quickLoad(fnDelegate)
{
DomLoadController.interval = setInterval(
function()
{
executeWhenReady(fnDelegate);
}
,DomLoadController.retryMilli);
}
And then all you need to do is call
function init()
{
//Initialization operations to be done when DOM loads
}

quickLoad(init);
Or use it like below (ruby/prototype-style), if it better suits your taste:
quickLoad(
function()
{
//initialization code goes here

}
);
Happy coding!

 bu yaziyi sevdin mi?  hemen una ekle!
 


2 Coments

somekool said...
woh !
this is one of the nicest JS tibits of code I got in a long time. thank you very much. it works like a charm. bye bye window.onload ;)
5:11 AM  
Volkan Ozcelik said...
if you like it you may consider trying

the most up-to-date version of sardalya

Cheers.
1:31 PM  


Post a Comment

Links to this post:


Create a Link

<< Home




Recent Posts

RSS

RSS register icon

Other Blogs

Various

Sponsor

Profile Information

Browser I Suggest

Sponsor

Dikkatimi Çekenler