Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 56 Β· Getting Started

Setup and Your First jQuery Script

Add jQuery to a page from a CDN with a pinned version and integrity check, learn the $ and jQuery names, and write your first working script safely.

jQuery is just a JavaScript file. To use it, you load that file on your page before your own code, and it creates two global names, jQuery and $, that your scripts can call. There is nothing to install or compile.

In this lesson you will load jQuery from a CDN, understand the integrity and crossorigin attributes that make that safe, write your first script and learn the one placement rule that causes most beginner errors.

Loading jQuery from a CDN

A CDN (content delivery network) hosts popular libraries on fast servers all over the world. Add a <script> tag that points at the file:

HTML
<script
  src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"
  integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo="
  crossorigin="anonymous"></script>

There are three details worth understanding:

  1. A pinned version. [email protected] names an exact release. Never write jquery@latest or leave the version off. A future major version could remove features, and your page would break without you changing a line.
  2. min.js. The minified file has whitespace and long names removed, so it downloads faster. The unminified jquery.js is only useful when you want to read the source.
  3. integrity and crossorigin. The integrity attribute is a Subresource Integrity hash of the exact file you expect. The browser downloads the file, hashes it and runs it only when the hashes match. If the CDN were hacked or the file corrupted, the browser would refuse it. Because the check needs to read the response, the request must be a CORS request, which is what crossorigin="anonymous" asks for.

You do not have to calculate the hash by hand. The jQuery download page and CDN pages show a ready-made <script> tag that includes the right integrity value. Copy the whole tag and keep the version number in sync with the hash.

The examples in this tutorial run in a sandbox, where we load the same file without the integrity attribute to keep the snippets short. On a real site, include it.

Downloading the file yourself

You can also download jquery.min.js, save it in your project, and load it from your own server:

HTML
<script src="/js/vendor/jquery-3.7.1.min.js"></script>

This avoids dependence on a third party, works offline, and lets a corporate network that blocks CDNs still run your site. The cost is that your server has to serve the file, although a good server caches it for a long time.

A popular compromise is a local fallback: try the CDN first, and if it failed, load the local copy.

HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script>
  window.jQuery || document.write('<script src="/js/vendor/jquery-3.7.1.min.js"><\/script>');
</script>

The second script checks whether window.jQuery exists. If the CDN did not respond, it writes a new script tag for the local file. The <\/script> spelling prevents the HTML parser from ending the outer script early. This pattern was very common; today many teams skip it and simply serve the file themselves.

CDN trade-offs

Before you pick a CDN link or a local file, weigh both sides.

What a CDN gives you

  • Lower load time. The file comes from a server near the visitor, and CDNs are built to serve static files fast.
  • Less load on your server. Your own bandwidth is spent on your pages, not on a 87 KB library.
  • Easy setup. One <script> tag, no build step, no file to keep in your repository.
  • Possible caching. A visitor who already has that exact URL cached can skip the download. Be careful with this one: modern browsers partition the cache by site, so a cached copy from another website is usually not reused any more. Do not count on it.

What a CDN costs you

  • An availability dependency. If the CDN is down, slow or blocked, your page loses jQuery and every script after it throws $ is not defined.
  • Regional restrictions. Some networks and countries block or throttle certain CDN hosts. A site that must work there needs its own copy.
  • Privacy and security exposure. A third party sees a request from every visitor, and if the file were ever tampered with, your site would run it. That is why the integrity attribute matters.
  • No offline use. An intranet page or an app that runs without internet cannot reach the CDN.
  • Version control is yours. A pinned URL never changes under you, but you must update the link, and the hash, yourself.

For a public site, a CDN with integrity plus a local fallback is a reasonable default. For an internal tool or a site that must work behind restrictive networks, host the file yourself.

The names jQuery and $

Once loaded, the library defines a single function in two spellings:

JavaScript
jQuery === $;   // true

$ is a plain shorthand for jQuery. They are the same function, so jQuery("p") and $("p") do the same thing. $ is a valid JavaScript identifier, nothing more. Other libraries, such as Prototype, also claim $; in that case you can call jQuery.noConflict() and keep using the long name, a topic covered in Using Plugins and jQuery UI.

The function also carries properties. The one you will use first is the version number:

Check that jQuery loaded

$.fn.jquery holds the version string of the loaded file. When you debug an odd problem on an old site, typing $.fn.jquery in the browser's console is the quickest way to learn which version you are really dealing with.

Your first script

Every jQuery statement follows the same shape: select elements with $(), then call a method on the result. Here is a complete page that does both, with the script placed after the elements it uses:

Select, then act

Read the code aloud: "when the element with id go is clicked, add the class shout to every element with class note, then change this button's text and disable it". .on() attaches the click handler; .addClass() acts on all three paragraphs at once; $(this) wraps the clicked button so we can call jQuery methods on it. These ideas get their own lessons later, so do not worry about memorizing them yet.

The script placement rule

jQuery can only find elements that already exist. Browsers read an HTML page from top to bottom, so the order of things matters. This broken example puts the script in the <head>, before the paragraph exists:

HTML
<head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
  <script>
    $("p").css("color", "red");   // finds nothing: no <p> has been parsed yet
  </script>
</head>
<body>
  <p>I stay black.</p>
</body>

Selecting an empty set does not cause an error. jQuery simply returns an empty collection and every method quietly does nothing. That silence is what makes this mistake confusing. Remember this rule:

  1. Load the jQuery file first.
  2. Run your own code after the elements it needs, or wrap it in a "document ready" handler.

The common solutions are putting your scripts at the end of <body>, or using the ready event, which is the topic of the next lesson.

A second ordering rule: any plugin that extends jQuery must come after jQuery and before the code that uses the plugin. If you ever see $ is not defined or jQuery is not defined, either the jQuery file failed to load, or a script that uses it appears above the tag that loads it.

Setup checklist

Pin the version Use [email protected], never latest.
Add integrity The browser verifies the file's hash.
jQuery first Plugins and your code come after it.
Elements first Place scripts after the HTML they use.

Most "jQuery does nothing" bugs break one of these four rules.

1 / 2

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why should you pin a version such as [email protected] instead of using "latest"?

    A pinned version gives you the exact file you tested. An automatic upgrade can break working code.
  2. 2. What does the integrity attribute on a script tag do?

    Subresource Integrity compares a hash of the downloaded file with the value you provided, so a tampered or corrupted file is not executed.
  3. 3. What is the relationship between $ and jQuery?

    $ === jQuery is true. $ is only a short alias.
  4. 4. Your script in the head runs $("p").css("color", "red") but nothing turns red and no error appears. Why?

    Selecting nothing returns an empty collection, and methods on an empty collection do nothing. Run the code after the elements exist.

Summary

  • Load jQuery with a <script> tag, using an exact version and, for CDN files, integrity and crossorigin="anonymous".
  • You can host the file yourself instead; a fallback to a local copy is an optional extra.
  • $ and jQuery are the same function; $.fn.jquery reports the loaded version.
  • Every statement selects elements and then calls methods on them.
  • Load jQuery first, and run your code only after the elements it uses exist.

Next, let's look at the document ready event, which makes that last rule easy to follow.