Tanzim Saqib on .NET discovery

January 4, 2008

ASP.NET AJAX Best Practices: Use more "var"

Filed under: AJAX, JavaScript — tanzimsaqib @ 11:03 am

Less use of “var” can result into wrong calculation as well as mistake in logic control. And also JavaScript interpreter finds it hard to determine the scope of the variable if var is not used. Consider the following simple JavaScript code:

function pageLoad()
{
    i = 10;
    loop();
    alert(i);   // here, i = 100
}

function loop()
{
    for(i=0; i<100; ++i)
    {
        // Some actions
    }
}

Here you see, the loop uses the variable i used before in pageLoad. So, it brings a wrong result. Unlike .NET code, in JavaScript variables can go along with the method calls. So, better not confuse the interpreter by using more “var” in your code:

function pageLoad()
{
    var i = 10;
    loop();
    alert(i);   // here, i = 10
}

function loop()
{
    for(var i=0; i<100; ++i)
    {
        // Some actions
    }
}

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
    }
);

« Newer Posts

Blog at WordPress.com.