JQuery-HTML Interaction

Posted: March 17, 2011 in Uncategorized

Including the jQuery Library Code in an HTML Page
Problem
You want to use the jQuery JavaScript library on a web page.
Solution
There are currently two ideal solutions for embedding the jQuery library in a web page:
• Use the Google-hosted content delivery network (CDN) to include a version of
jQuery (used in this chapter).
• Download your own version of jQuery from jQuery.com and host it on your own
server or local filesystem.
Discussion
Including the jQuery JavaScript library isn’t any different from including any other
external JavaScript file. You simply use the HTML <script> element and provide the
element a value (URL or directory path) for its src=”” attribute, and the external file
you are linking to will be included in the web page. For example, the following is a
template that includes the jQuery library that you can use to start any jQuery project:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<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&gt;
</head>
<body>
<script type=”text/JavaScript”>
alert(‘jQuery ‘ + jQuery.fn.jquery);
</script>
</body>
</html>
Notice that I am using—and highly recommend using for public web pages—the
Google-hosted minified version of jQuery. However, debugging JavaScript errors in
minified code is not ideal. During code development, or on the production site, it actually
might be better to use the nonminified version from Google for the purpose of
debugging potential JavaScript errors. For more information about using the Googlehosted
version of jQuery, you can visit the Ajax libraries API site on the Web at http://
code.google.com/apis/ajaxlibs/.
It’s of course also possible, and mostly likely old hat, to host a copy of the jQuery code
yourself. In most circumstances, however, this would be silly to do because Google has
been kind enough to host it for you. By using a Google-hosted version of jQuery, you
benefit from a stable, reliable, high-speed, and globally available copy of jQuery. As
well, you reap the benefit of decreased latency, increased parallelism, and better caching.
This of course could be accomplished without using Google’s solution, but it would
most likely cost you a dime or two.
Now, for whatever reason, you might not want to use the Google-hosted version of
jQuery. You might want a customized version of jQuery, or your usage might not
require/have access to an Internet connection. Or, you simply might believe that Google
is “The Man” and wish not to submit to usage because you are a control freak and
conspiracy fanatic. So, for those who do not need, or simply who do not want, to use
a Google-hosted copy of the jQuery code, jQuery can be downloaded from
jQuery.com and hosted locally on your own server or local filesystem. Based on the
template I’ve provided in this recipe, you would simply replace the src attribute value
with a URL or directory path to the location of the jQuery JavaScript file you’ve downloaded.

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 timeconsuming
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”&gt;
<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&gt;
<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”&gt;
<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&gt;
<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”&gt;
<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&gt;
<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.

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