Methods for loading your Jquery script

Tags

, ,


jQuery offers two powerful methods to execute code and attach event handlers: $(document).ready and $(window).load. The document ready event executes already when the HTML-Document is loaded and the DOM is ready, even if all the graphics haven’t loaded yet. If you want to hook up your events for certain elements before the window loads, then $(document).ready is the right place.

$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready");
});

Back in the day of heavy server frameworks, knowing that your page was fully constructed before you tried to mutate it was a big deal. This was especially true if you were using partial views of some sort that were injected into the layout/master page by the server at runtime.

Nowadays, it’s considered best practice to include your scripts at the bottom of the page. The HTML5 async attribute notwithstanding, scripts are loaded and executed synchronously by the browser. That means that if you have a large script in the head of your page, it will delay loading of the DOM and make your page seem slower than it actually is. Loading all scripts last will at least make your application seem to load faster. It also gives you a chance to use a spinner or loading overlay if you are completely dependent on JavaScript for your UI.

If you are adhering to the “scripts at the bottom” best practice, then you have no need for jQuery’s document ready function as the HTML is already loaded by the time the script is run.

This element is on the page BEFORE all the scripts. No document ready needed.

// if you include your scripts at the very bottom, you don't need document ready
(function($) {

$("#zack").css("color", "green");
$("#slator").css("color", "red");

}(jQuery));

The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself.


$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
alert("window is loaded");
});

Follow

Get every new post delivered to your Inbox.

Join 64 other followers