Wednesday 9 September 2009

Preventing Page Navigation While an AJAX Queue is Working

AJAX is quick. As internet technologies go, it's as fast a server call as you're likely to make. This having been said, it's not instantaneous. While the callback is occurring there is plenty of time for your users to do stuff you'd rather they didn't, such as navigating away from the page or closing the browser altogether. If you've implemented a good, scalable AJAX solution for your custom calls and built a queuing object, then there might even be server calls which haven't been initiated by the time the user decides to move onto the next screen in your application.

There is a solution to this problem. The following method takes care of processing links while making sure that an AJAX queue has finished running.

function doNav(path)
{
    if(ajaxQueue.running)
    {
        setTimeout('doNav(path)', 50);
    }
    else window.location = path;
}

This method assumes that the queue object is called ajaxQueue and this has a boolean property named 'running'. The reason we call setTimeout is because JavaScript isn't threaded in the same way as some server side languages. If you don't call setTimeout and instead call doNav with direct recursion, the script engine will enter an infinite loop as the thread will never allow the queue processing time to complete its task. The call to setTimeout here will cause the thread to let other things to get on with their job for 50 milliseconds and then, once the script engine completes the task it is currently running (setTimeout doesn't exactly time the process by 50 ms, it does guarantee a minimum of 50 ms however) doNav will be fired again.

Directing all page navigation in your AJAX application through a method like doNav will help make your application more robust and reliable.



No comments:

Post a Comment