Adding jQuery to a Webpage
In this page:
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
<!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
<!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
<!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
<!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
<!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: