Home > Articles > Web Development > Ajax and JavaScript

  • Print
  • + Share This
Like this article? We recommend Early 'Page Ready' Event

Early 'Page Ready' Event

All web browsers, starting with very early versions of Internet Explorer and Netscape, fire the document.onload event when the web page completes its loading process. If you believe in the principles of progressive enhancement (and you should), you can use this event to modify the web page's appearance or attach events to individual elements. The "only" problem is the timing of the onload event: It fires when the last image and applet finish loading, by which time the user might have been looking at the web page for a few seconds. Modifying the DOM tree at that time can result in visible screen flicker.

Some modern browsers provide a browser-specific event that's fired as soon as the DOM content is loaded and ready to be manipulated. The jQuery library provides a browser-independent interface, using the jQuery.ready() method, that allows you to execute your JavaScript code safely at the earliest possible time. The main jQuery function supports a convenient shortcut: When called with the function argument jQuery(callback), it registers the callback function with the ready event. When combined with the jQuery shortcut ($) and anonymous JavaScript functions, the resulting code looks a bit cryptic, but once you get used to it, it becomes readable and highly efficient:

  /* insert the page initialization code */

Furthermore, since jQuery allows event-handler chaining, you can register multiple chunks of JavaScript code with the ready event, resulting in a highly scalable solution.

  • + Share This
  • 🔖 Save To Your Account