Cover by Cody Lindley

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

1.2. Executing jQuery/JavaScript Coded After the DOM Has Loaded but Before Complete Page Load

Problem

Modern JavaScript applications using unobtrusive JavaScript methodologies typically execute JavaScript code only after the DOM has been completely loaded. And the reality of the situation is that any DOM traversing and manipulation will require that the DOM is loaded before it can be operated on. What’s needed is a way to determine when the client, most often a web browser, has completely loaded the DOM but has possibly not yet completely loaded all assets such as images and SWF files. If we were to use the window.onload event in this situation, the entire document including all assets would need to be completely loaded before the onload event fired. That’s just too time-consuming for most web surfers. What’s needed is an event that will tell us when the DOM alone is ready to be traversed and manipulated.

Solution

jQuery provides the ready() method, which is a custom event handler that is typically bound to the DOM’s document object. The ready() method is passed a single parameter, a function, that contains the JavaScript code that should be executed once the DOM is ready to be traversed and manipulated. The following is a simple example of this event opening an alert() window once the DOM is ready but before the page is completely loaded:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script type="text/JavaScript">
    jQuery(document).ready(function(){//DOM not loaded, must use ready event
        alert(jQuery('p').text());
    });
</script>
</head>
<body>
<p>The DOM is ready!</p>
</body>
</html>

Discussion

The ready() event handler method is jQuery’s replacement for using the JavaScript core window.onload event. It can be used as many times as you like. When using this custom event, it’s advisable that it be included in your web pages after the inclusion of stylesheet declarations and includes. Doing this will ensure that all element properties are correctly defined before any jQuery code or JavaScript code will be executed by the ready() event.

Additionally, the jQuery function itself provides a shortcut for using the jQuery custom ready event. Using this shortcut, the following alert() example can be rewritten like so:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
    jQuery(function(){ //DOM not loaded, must use ready event
        alert(jQuery('p').text());
    });
</script>
</head>
<body>
<p>The DOM is ready!</p>
</body>
</html>

The use of this custom jQuery event is necessary only if JavaScript has to be embedded in the document flow at the top of the page and encapsulated in the <head> element. I simply avoid the usage of the ready() event by placing all JavaScript includes and inline code before the closing <body> element. I do this for two reasons.

First, modern optimization techniques have declared that pages load faster when the JavaScript is loaded by the browser at the end of a page parse. In other words, if you put JavaScript code at the bottom of a web page, then the browser will load everything in front of it before it loads the JavaScript. This is a good thing because most browsers will typically stop processing other loading initiatives until the JavaScript engine has compiled the JavaScript contained in a web page. It’s sort of a bottleneck in a sense that you have JavaScript at the top of a web page document. I realize that for some situations it’s easier to place JavaScript in the <head> element. But honestly, I’ve never seen a situation where this is absolutely required. Any obstacle that I’ve encountered during my development by placing JavaScript at the bottom of the page has been easily overcome and well worth the optimization gains.

Second, if speedy web pages are our goal, why wrap more functionality around a situation that can be elevated by simply moving the code to the bottom of the page? When given the choice between more code or less code, I choose less code. Not using the ready() event results in using less code, especially since less code always runs faster than more code.

With some rationale out of the way, here is an example of our alert() code that does not use the ready() event:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>The DOM is ready!</p>
<script type="text/JavaScript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
     alert(jQuery('p').text());//go for it the DOM is loaded
</script>
</body>
</html>

Notice that I have placed all of my JavaScript before the closing </body> element. Any additional markup should be placed above the JavaScript in the HTML document.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required