Tanzim Saqib on .NET discovery

February 6, 2007

JavaScript execution before the page has finished loading

Filed under: JavaScript, Performance — tanzimsaqib @ 8:58 pm

When a webpage loads, it fetches the stylesheets, javascript, images, other objects etc. So, when it is done, it’s already late and user may complain about the site’s poor speed of execution. One way you can make it faster, you can start JavaScript execution immediately right after the HTML DOM has finished loading and ready to traverse, before the images.

// Introduce our custom event onDOMReady
window.onDOMReady = DOMReady  

function DOMReady(fn)
{
    // According to standard implementation
     if(document.addEventListener)
        document.addEventListener("DOMContentLoaded", fn, false);  

    // IE
    else
        document.onreadystatechange = function()
            {
                checkReadyState(fn);
            }
}  

function checkReadyState(fn)
{
    if(document.readyState == "interactive")
        fn();
}  

window.onDOMReady(
    function()
    {
        // DOM is loaded
        // So start JavaScript execution
    }
);

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.