A Better Pattern For Ajax On Pageload

Before I give you a better pattern for ajax on page load. Let me tell you a little about what is Ajax.

AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX just uses a combination of:

  • A browser built-in XMLHttpRequest object (to request data from a web server)
  • JavaScript and HTML DOM (to display or use the data)

AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally common to transport data as plain text or JSON text.

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

So now we can talk about the post title “A better pattern For Ajax On Pageload”

Let’s 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 that attaches the result from the ajax call to the DOM.

Here is a better pattern, for 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.