things out, learning about JavaScript features, and even modifying your program
temporarily.
jQuery
We’re going to add an extremely popular client-side scripting library called jQuery to
our page. While it is not necessary, or even germane to the task at hand, it is such a
ubiquitous library that it is often the first one you will include in your web code. Even
though we could easily get by without it in this example, the sooner you start getting
accustomed to seeing jQuery code, the better off you will be.
At the end of the body, before we include our own main.js, we’ll link in jQuery:
<
script
src
=
"https://code.jquery.com/jquery-2.1.1.min.js"
></
script
>
<
script
src
=
"main.js"
></
script
>
You’ll notice that we’re using an Internet URL, which means your page won’t work
correctly without Internet access. We’re linking in jQuery from a publicly hosted con‐
tent delivery network (CDN), which has certain performance advantages. If you will
be working on your project offline, you’ll have to download the file and link it from
your computer instead. Now we’ll modify our main.js file to take advantage of one of
jQuery’s features:
$
(
document
).
ready
(
function
() {
'use strict'
;
console
.
log
(
'main.js loaded'
);
});
Unless you’ve already had some experience with jQuery, this probably looks like gib‐
berish. There’s actually a lot going on here that won’t become clear until much later.
What jQuery is doing for us here is making sure that the browser has loaded all of the
HTML before executing our JavaScript (which is currently just a single
console.log
).
Whenever we’re working with browser-based JavaScript, we’ll be doing this just to
establish the practice: any JavaScript you write will go between the
$(docu
ment).ready(function() {
and
});
lines. Also note the line
'use strict'
; this is
something we’ll learn more about later, but basically this tells the JavaScript inter‐
preter to treat your code more rigorously. While that may not sound like a good thing
at first, it actually helps you write better JavaScript, and prevents common and
difficult-to-diagnose problems. We’ll certainly be learning to write very rigorous Java‐
Script in this book!
8 | Chapter 1: Your First Application