← Back to jQuery Course | Chapter 1: Getting Started | Lesson 2 of 6

Adding jQuery to a Webpage

You can load jQuery from a CDN by adding a script element.

Add the CDN Script

A script tag pointing at a public CDN URL downloads the jQuery library file before your page runs, with no local install needed. This is the fastest way to get started, since there's nothing to download or configure locally.

Example: Add the CDN Script

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
  </body>
</html>

Run jQuery Code

Once the CDN script tag has loaded jQuery into the page, the global $ function becomes available to any script that runs afterward. Using $() to select elements is the first thing most developers try to confirm the library loaded correctly.

Example: Run jQuery Code

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <script>
      console.log($("body").length);
    </script>
  </body>
</html>

Place Your Script

Your own script tag must come after the jQuery CDN tag in the HTML, or the browser will throw a '$ is not defined' error the moment your code runs. Keeping load order correct is one of the most common early mistakes with CDN-based setups.

Example: Place Your Script

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
      console.log($.fn.jquery);
    </script>
  </head>
  <body></body>
</html>

Use a Button

Wiring a button to a click handler is a quick way to prove the whole setup works end-to-end -- if the console logs a message when you click, both the CDN load and your script are wired up correctly.

Example: Use a Button

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <button id="test">Test</button>
    <script>
      $("#test").click(function() {
      console.log("jQuery is working");
      });
    </script>
  </body>
</html>

Check That jQuery Loaded

Logging jQuery.fn.jquery or $.fn.jquery to the console prints the exact version string of the loaded library, which is useful for confirming you got the version you expected from the CDN, especially when debugging a compatibility issue.

Example: Check That jQuery Loaded

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <script>
      console.log($.fn.jquery);
      console.log(jQuery.fn.jquery);
    </script>
  </body>
</html>
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.