jQuery Get Started
Getting started with jQuery means adding the library to your page and confirming it runs before your code does.
Adding jQuery to a page
There are two common ways to include jQuery in a web page. You can download the library and host the file yourself, or you can link to a copy served by a content delivery network (CDN). Both give you the same jQuery; the difference is only where the file comes from.
- Downloaded file: you keep a copy of jquery.min.js in your project and reference it locally.
- CDN link: you point a script tag at a hosted URL, which can load faster for returning visitors because the file may already be cached.
Linking the library
Whichever source you choose, you add jQuery with a script tag inside your HTML, usually just before the closing body tag. Place it before any of your own scripts that rely on jQuery, so the library is defined by the time your code runs.
Including jQuery from a CDN
<!DOCTYPE html>
<html>
<head>
<title>My jQuery Page</title>
</head>
<body>
<button>Click me</button>
<p>Waiting...</p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("p").text("Ready and running!");
});
});
</script>
</body>
</html>Waiting for the page to load
Your code should run only after the browser has finished building the page, otherwise the elements you try to select may not exist yet. The document ready wrapper delays your code until that point. jQuery also offers a shorter form that does the same thing.
The shorthand ready wrapper
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<h1>Hello</h1>
<script>
$(function () {
$("h1").css("color", "teal");
});
</script>
</body>
</html>Exercise: jQuery Get Started
Where should the jQuery script reference generally go relative to your own custom script?