So what is wrong with the window.onload event? Well for many years I, just like many other developers, thought window.onload was prefectly fine and was exactly what I needed. Well I don’t think that is true any longer. The problem is that if you have a page with large files like images, animations, or video then there will be a huge delay before your code gets executed. The onload event does not fire until every last piece of the page is loaded.

That isn’t what we want. We just want to wait until the DOM is loaded and is able to be manipulated. So how do we do this? Well, below if the code you need to do just that. The onDomReady event accepts a function as a parameter and that function gets executed as soon as the DOM is available and before the rest of the media is done loading.

This will result in more responsive code and less delay in execution.


//create onDomReady Event
window.onDomReady = DomReady;

//Setup the event
function DomReady(fn)
{
	//W3C
	if(document.addEventListener)
	{
		document.addEventListener("DOMContentLoaded", fn, false);
	}
	//IE
	else
	{
		document.onreadystatechange = function(){readyState(fn)}
	}
}

//IE execute function
function readyState(fn)
{
	//dom is ready for interaction
	if(document.readyState == "interactive")
	{
		fn();
	}
}

Once you have included the above code in your page you can use it in a similar manner as below.


//execute as soon as DOM is loaded
window.onDomReady(onReady);

//do on ready
function onReady()
{
	alert("The DOM is ready!");
}