HTML5 and CSS3, Second Edition

(singke) #1
We could wrap our code in the window.onLoad() event handler, but that event
gets fired after all the content has loaded. This could cause a delay, meaning
your users could be interacting with things before your events have been
attached. We need a way to add our events when the DOM is loaded but before
it’s been displayed.

jQuery’s document.ready() event handler does exactly this, in a way that works
across browsers. We use it like this:

jqueryprimer/ready.html
$(document).ready(function() {
alert("Hi!I am a popupthatdisplayswhenthe pageloads");
});

There’s a shorthand version that you’ll see a lot, which looks like this:


jqueryprimer/ready.html
$(function() {
alert("Hi!I am a popupthatdisplayswhenthe pageloads");
});

Loading scripts with document.ready() is an extremely popular design pattern in
JavaScript apps. However, often we can avoid this altogether by placing the
calls to external scripts at the bottom of the page, right before the closing
<body> tag. As long as no scripts are asynchronously changing the DOM, we
don’t need to worry. But in cases where we don’t control the load order of
scripts, or elements are getting created on the fly, using document.ready() is the
right choice.

A2.7 Use jQuery Wisely


jQuery is a big library and isn’t always necessary. If you have a page where
you only need to locate an element by its ID, stick with

navbar= document.getElementById("#navbar");

Loading jQuery for one or two things might be overkill. Modern browsers can
already do a lot of what jQuery does with methods like document.querySelector()
and document.querySelectorAll(), which are used in modern browsers to select ele-
ments using CSS selector syntax much like jQuery does:

links= document.querySelectorAll("a.popup");

Use jQuery when it makes your life easier, but don’t be afraid to leave it out
when that makes more sense.

This is only a small sample of what we can do with jQuery. Aside from the
document-manipulation features, jQuery provides methods for serializing

Appendix 2. jQuery Primer • 270


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf