A better pattern for ajax on pageload

Jan 03 2013

Lets say you are making an ajax call on the page load:

Can you find any problem with that piece of code?

You are right! The problem is that here the ajax call is initiated only after the DOM.ready event is fired, while in fact it can be initiated before the DOM.ready, since it does not have any dependency on DOM.ready.

The only piece of code which has a dependency on DOM.ready is the one which attaches the result from the ajax call to the DOM.

Here is a better pattern, solving these problems:

As you can see, the ajax call is initiated even before the DOM.ready event and when the result arrives, then we wait till DOM.ready before modifying the DOM based on the data received.

Let me know if you have any better way of doing this.

7 responses so far

Leave a Reply