Learning Curve…

jQuery ready function …

Posted on: October 10, 2011

Most of the jQuery code we write executed when the browser is done loading the page. It’s important to wait with executing your code until the page is done loading the DOM. The DOM — the document object model — is a hierarchical representation of your web page and contains a tree-like structure of all your HTML elements, script files, CSS, images, and so on.

The DOM is always in sync with the page you see in the browser, so if you make a programmatic change to the DOM (for example, with jQuery code), the change is reflected in the page in the browser. If you execute your jQuery code too early (for example, at the very top of the page), the DOM may not have loaded the elements you’re referring to in your script, and you may get errors. Fortunately, it’s easy to postpone the execution of your code until the DOM is ready using the ready function in jQuery:

$(document).ready(function() {

// Code added here is executed when the DOM is ready.

});

Any code we add between the opening and closing curly brace is executed when the page is ready for DOM manipulation. JQuery also comes with a shortcut for the ready function to make it easier to write code that fires when the DOM is ready. The following snippet is equivalent to the preceding example:

$(function() {

// Code added here is executed when the DOM is ready.

});

Because jQuery code is often specific to a page, it makes sense to add the code to the end of just the pages that require it. To make this a little easier, we can add a ContentPlaceHolder in your master page especially for this purpose. The pages that use this master page then have an easy location to write jQuery code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Learning days (Calendar)

October 2011
M T W T F S S
« Sep   Nov »
 12
3456789
10111213141516
17181920212223
24252627282930
31  

Knowledge Bank (Archives)

I am on Twitter

Blog Stats

  • 498,754 hits

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 43 other followers

%d bloggers like this: