10.07.2017 Views

246996016-HTML5-Step-by-Step

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

294 Chapter 16<br />

However, as just noted, it’s recommended to host the file yourself for production purposes<br />

on live sites rather than relying on the CDN. There’s nothing worse than having<br />

your Web site up and operational but reliant on a CDN-based library Web site that is<br />

down. For the purposes of this chapter though, it’s perfectly acceptable to use the CDNbased<br />

version rather than downloading jQuery yourself. Most of the examples in this<br />

chapter assume that you have downloaded jQuery locally and adjusted the version number<br />

to fit the version that you downloaded. If you’d like to use the CDN-based version<br />

see http://docs.jquery.com/Downloading jQuery#CDN Hosted jQuery for the current URL.<br />

Getting Ready for jQuery<br />

Imagine this problem: You’ve written some JavaScript and included it just before the closing<br />

tag as shown earlier in the chapter. One of the things that your JavaScript<br />

does is change an image on the page. The problem is that your image hasn’t loaded, so<br />

now the JavaScript runtime can’t find it, and the page loads incorrectly.<br />

The root cause of this all-too-common problem is that browsers execute JavaScript as<br />

they encounter scripts on the page. So even though the JavaScript is at the bottom of the<br />

page, the browser may not have loaded the entire page prior to running the JavaScript.<br />

In other words, the document isn’t ready <strong>by</strong> the time the JavaScript runs, so chaos<br />

ensues.<br />

A workaround for this problem is to use an onload or load event on the page, but even<br />

that is fraught with danger, not to mention it’s bad practice. Luckily, jQuery includes<br />

a function called .ready() which executes only after the page has been loaded <strong>by</strong> the<br />

browser and is ready for JavaScript code to be run. The .ready() function is a simple<br />

way to execute JavaScript while safely knowing that all elements of the page have been<br />

loaded and are ready to use. jQuery code begins with a dollar sign and parentheses, as<br />

you’ll see in the upcoming example.<br />

Using the .ready() function is easy. The following code shows an example of the .ready()<br />

function in action.<br />

<br />

<br />

<br />

Document Ready<br />

<br />

<br />

<br />

<br />

$(document).ready(alert('Hello Again'));<br />

<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!