Getting started with jQuery: a small, maintainable pattern
jQuery is a JavaScript library for selecting and updating DOM elements, handling browser events, and working with asynchronous requests. It remains common in older sites and in applications whose plugins depend on it. Before adding it to a new project, check whether the browser APIs you need are already sufficient.
Load one pinned version
Use the official CDN or install the package from npm. Pin a specific version, keep the script before code that uses it, and review breaking changes before moving between major versions. This example uses jQuery 4.0.0; use the current official download page to select a version that matches your browser support and other dependencies.
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script src="/js/app.js" defer></script>
When scripts use defer, keep their document order: dependencies must appear before the scripts that depend on them. If your app needs older browser support, check the jQuery release notes and choose an appropriate build instead of assuming the newest major version will fit.
Select elements and respond to events
Use stable IDs or classes rather than selecting every element of a broad type. Delegated events are useful for controls that may be added after page load. This example updates a message using .text(), which treats the value as text rather than HTML.
<button id="show-status" type="button">Show status</button>
<p id="status" aria-live="polite"></p>
<script>
$(function () {
$("#show-status").on("click", function () {
$("#status").text("The button was pressed.");
});
});
</script>
For content that is not trusted, avoid inserting it with .html(). Inserting untrusted strings as HTML can create cross-site scripting vulnerabilities.
Send and handle a JSON request
$.ajax() lets you state the request method, expected response type, and error path explicitly. The server must allow this request and return valid JSON with an appropriate response status.
$.ajax({
url: "/api/items",
method: "GET",
dataType: "json"
})
.done(function (items) {
$("#status").text("Loaded " + items.length + " items.");
})
.fail(function (xhr, status, error) {
$("#status").text("Could not load items (" + status + ").");
console.error(error);
});
Add a plugin carefully
Load the exact plugin build after jQuery, then follow that plugin’s own setup guide. Confirm the plugin’s supported jQuery versions, licence, release history, keyboard behaviour, and maintenance status. Test the feature with keyboard-only input and at mobile widths. Do not load two different jQuery copies on the same page: plugins may attach to one copy while your application calls another.
For the official project and release notes, visit jQuery downloads and the jQuery project blog.