Loading jQuery and running code
To use jQuery, the library file has to be loaded on the page. The easiest way is a CDN, a server that hosts popular libraries. Your own code then runs once the page is built.
Project structure
jQuery needs no special project generator. Create a todo folder with two files:
todo/
├── index.html
└── script.jsindex.html holds the markup, script.js holds your code.
Loading from a CDN
Create index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My tasks</title>
</head>
<body>
<h1>My tasks</h1>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="script.js"></script>
</body>
</html>The first <script> loads jQuery from the official CDN, the second loads your file. Open index.html in the browser, and typing $.fn.jquery in the developer console shows the version 3.7.1.
A file with .min in its name is the compressed version without spaces and comments. It is smaller, so websites use it.
Running code after the page loads
If a script is included in <head>, it runs before the browser reads <body>, and the elements do not exist yet. That is why jQuery code is usually wrapped in $(function () { ... }). Create script.js:
// script.js
$(function () {
$('h1').text('To-do list');
console.log('Page is ready');
});The function passed to $ is called once all the HTML has been parsed. Older code uses a longer form of the same thing: $(document).ready(function () { ... }).
In the live examples of this course the script sits at the end of the page, after the markup, so they do not need the wrapper. Examples for script.js include it.
The same in plain JavaScript
// script.js
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('h1').textContent = 'To-do list';
});Installing with npm
In a project with a bundler such as Vite, jQuery is installed as a package:
npm install jqueryAnd imported where needed:
// src/main.js
import $ from 'jquery';
$(function () {
$('h1').text('To-do list');
});The bundler puts the library into the final file, so no separate <script> tag is needed.
Common mistake
Loading jQuery twice on one page: for example, the site theme already loads the library and you add another tag. The second copy replaces the first, and plugins registered on the first copy disappear, giving an error like $(...).slider is not a function. Before adding jQuery, check in the console whether $.fn.jquery already exists.