Add a script tag
Put two files in the same folder: the page (index.html) and the script (script.js). The
<script> line in the head connects them. src says where the file is, the same way
src works on an image.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first script</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Hello, JavaScript</h1>
<button type="button" id="hello-btn">Say hello</button>
<p id="message"></p>
</body>
</html> const button = document.getElementById('hello-btn');
const message = document.getElementById('message');
let clicks = 0;
button.addEventListener('click', () => {
clicks = clicks + 1;
message.textContent = 'Hello! Clicks so far: ' + clicks;
});
Open index.html in your browser and click the button. The line under it should count your clicks. If
you haven’t made an HTML file before, how to create an HTML file shows you
how to save one on Windows or a Mac (and how to dodge the .txt trap, which bites script files too).
-
A script tag always needs its closing
</script>, even when there’s nothing between the tags.<script src="script.js" />doesn’t work in HTML. Here’s what it breaks. -
The
.jsfile holds only JavaScript. No<script>tags inside it, and no HTML. -
deferis a yes/no attribute, so writing the word is enough.defer="true"works too, but so woulddefer="false", which surprises people: if the word is there, it’s on.
Try it in the HTML Editor
The live boxes on our tutorial pages keep JavaScript switched off, so the examples on this page are code you copy. To see one run without saving any files, use the HTML Editor:
- Paste the HTML into the HTML tab, for example:
For the HTML tab <h1>Hello, JavaScript</h1> <button type="button" id="hello-btn">Say hello</button> <p id="message"></p> - Paste
script.jsfrom above into the JS tab. - Leave the JavaScript box ticked and press Run (or Ctrl+Enter). Click “Say hello” in the preview.
The editor puts the JS tab’s code at the end of the page for you, so you don’t need a script tag there. A full page with an inline script, like the coffee counter below, can go straight into the HTML tab.
An external .js file or a script block
JavaScript can live in its own file (external) or right in the page between <script> and
</script> (inline). It’s the same language either way.
An external file with src
<script src="script.js" defer></script>
This is what most sites do. Every page that needs the code links the same file, so a fix in
script.js fixes all of them, and the browser keeps a copy so the next page loads faster.
Inline JavaScript in a script block
<button type="button" id="hello-btn">Say hello</button>
<p id="message"></p>
<script>
document.getElementById('hello-btn').addEventListener('click', () => {
document.getElementById('message').textContent = 'Hello, Sam!';
});
</script>
No src, the code goes between the tags. It only works on this one page. Good for a small demo, or a
page you want to send to someone as a single file, like this one:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Coffee counter</title>
</head>
<body>
<h1>Coffees today: <span id="count">0</span></h1>
<button type="button" id="add-btn">I had another one</button>
<script>
let coffees = 0;
document.getElementById('add-btn').addEventListener('click', () => {
coffees = coffees + 1;
document.getElementById('count').textContent = coffees;
});
</script>
</body>
</html>
Pick one per tag, though. A script tag with src ignores anything written between its tags, so
<script src="script.js">alert('Hi')</script> loads the file and never shows the alert. Use
two separate tags if you need both.
Where to put the script tag in HTML
The browser reads your HTML from top to bottom. A plain script tag (no defer) runs the moment the
browser reaches it, and the rest of the page waits. So a script in the head runs before the body exists:
<head>
<script src="script.js"></script>
</head>
<body>
<button type="button" id="hello-btn">Say hello</button>
</body>
When script.js from the top of the page runs here, getElementById('hello-btn') finds nothing,
because the button isn’t on the page yet. You get null, and the console shows
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener'). It’s the most
common error in a first script. There are three ways out, and any one of them is enough.
1. Keep it in the head and add defer
<head>
<script src="script.js" defer></script>
</head> The file downloads while the page loads, and runs once all the HTML has been read. This is the usual choice today: the script starts downloading early, and it never runs too soon.
2. Put it at the end of the body
<body>
<button type="button" id="hello-btn">Say hello</button>
<script src="script.js"></script>
</body> By the time the browser gets here, everything above is already on the page. This is the older habit, and you’ll see it in plenty of tutorials. It works fine, the file just starts downloading a little later.
3. Wait for the page in your code
document.addEventListener('DOMContentLoaded', () => {
const button = document.getElementById('hello-btn');
button.addEventListener('click', () => alert('Hello!'));
}); DOMContentLoaded fires when the HTML has been read, so the code inside waits for the button. Use this when
you can’t change the script tag, for example in a site builder that only lets you paste code into the head.
defer, async and type="module"
Three attributes change when a script runs. With any of them, the file downloads while the browser keeps reading the page, so the page isn’t held up by the download. Here they are side by side:
<script src="menu.js"></script>
<script src="menu.js" defer></script>
<script src="https://example.com/visitor-stats.js" async></script>
<script type="module" src="main.js"></script> | Tag | When it runs | Good for |
|---|---|---|
| No attribute | Right where it is. The page stops and waits while the file downloads and runs. | A script at the end of the body |
defer | After all the HTML is read, in the order you wrote the tags | Your own scripts. The safe default. |
async | As soon as it arrives, maybe before the HTML is done, in any order | Scripts that don’t touch your page or other scripts, like visitor stats |
type="module" | Like defer: after the HTML, in order | Code split into files with import and export |
-
deferandasynconly work on tags withsrc(for classic scripts). On an inline<script>they’re ignored, and the code runs right where it is. -
Order matters with
async. Ifscript.jsuses a library and both are async, the library may not be there yet when your code runs. Usedeferon both and they run in order. -
Module scripts don’t need
defer, they wait anyway. They also run in strict mode, which turns some quiet mistakes (like using a variable you never declared) into errors.
A small module example
With type="module", one file can hand a function to another. Link only main.js in the page:
<script type="module" src="main.js"></script>.
export function greet(name) {
return 'Hello, ' + name + '!';
} import { greet } from './greet.js';
document.getElementById('message').textContent = greet('Sam'); - Write the path with
./in front:'./greet.js'. A plain'greet.js'fails. -
Modules need a web server. If you double-click the HTML file, the browser blocks module files. In Chrome and Edge
the console shows a CORS error that mentions
origin 'null'. Run a small local server instead (VS Code’s Live Server extension is a popular one), or stick with plaindeferscripts while you learn.
My JavaScript isn’t running: a checklist
First, open the Console. It’s where the browser writes JavaScript errors, with the file name and line number, and you can’t really debug without it. Open the page, use the shortcut for your browser, then reload.
| Browser | Windows / Linux | Mac |
|---|---|---|
| Chrome, Edge | F12, or Ctrl+Shift+J for the Console | Cmd+Option+J |
| Firefox | F12, or Ctrl+Shift+K for the Console | Cmd+Option+K |
| Safari | Not available | Tick “Show features for web developers” in Settings > Advanced, then Cmd+Option+C |
A red line that names script.js with something like ERR_FILE_NOT_FOUND or
404 means the browser couldn’t find the file. A red line pointing at a line inside your file means it
loaded and the code has a problem. And no message at all usually means the tag itself is off. Go down this list:
- The path is wrong.
srcis a path from the HTML file to the .js file. A script in ajsfolder issrc="js/script.js", and from a page in a subfolder it’ssrc="../js/script.js". Spelling counts:Script.jsandscript.jsare different files on most web servers. The paths work the same as the ones for CSS, see the file path table. - The file is really called script.js.txt. Notepad likes to add
.txt, and TextEdit saves.rtfunless it’s in plain-text mode (how to switch). Windows also hides file extensions by default. On Windows 11, open File Explorer and turn on View > Show > File name extensions. On a Mac, turn on Finder > Settings > Advanced > Show all filename extensions. - The script runs before the element exists. The
Cannot read properties of nullerror. Adddeferor move the tag to the end of the body, as shown above. - One mistake stops the whole file. A missing quote, like
alert('Hello);, is a syntax error (Invalid or unexpected token), and then none of the file runs, not even the lines above it. An error while the code runs is different: everything before it worked, everything after it is skipped. The console tells you which line. - The script tag is self-closed.
<script src="menu.js" />looks finished, but HTML ignores that slash. The tag stays open, and everything after it, up to the next</script>, becomes part of it. The HTML in between disappears and the next script never loads. In the broken version below, the menu line is gone andprices.jsnever runs.
<h2>Coffee menu</h2>
<script src="menu.js" />
<p>Espresso, latte, mocha.</p>
<script src="prices.js"></script>
<p>Open 8 to 4.</p> Coffee menu
Open 8 to 4.
<h2>Coffee menu</h2>
<script src="menu.js"></script>
<p>Espresso, latte, mocha.</p>
<script src="prices.js"></script>
<p>Open 8 to 4.</p> Coffee menu
Espresso, latte, mocha.
Open 8 to 4.
- A typo in the tag. It’s
src, nothreforscr. And a misspelled type, liketype="text/javascipt", quietly stops the script: the browser treats anything it doesn’t know as data, not code. Easiest fix: delete the type attribute (you don’t need it). - </script> inside your inline code. In a script block, the text
'</script>'ends the block, even inside quotes. Write it as'<\/script>', or move the code into a .js file where this can’t happen. - The browser is showing an old copy. Browsers cache .js files. Do a hard refresh: Ctrl+F5 or
Ctrl+Shift+R on Windows and Linux, Cmd+Shift+R on a Mac in Chrome, Edge or Firefox, Option+Cmd+R in Safari. On a
live site,
src="script.js?v=2"with a new number each time also does the trick. - A module function isn’t found. Functions inside a
type="module"script aren’t visible to the rest of the page, soonclick="sayHello()"fails withsayHello is not defined. Use addEventListener inside the module instead.
Do you need type="text/javascript"?
<script type="text/javascript" src="script.js"></script>
<script src="script.js"></script>
No. JavaScript is the default, so the second line is all you need. You’ll still see
type="text/javascript" in older code and in some copy-paste snippets, and it does no harm when it’s
spelled right. The one type worth writing today is type="module".
onclick in HTML or addEventListener
There are two common ways to make a button do something. You can write the call right in the HTML with an
onclick attribute:
<button type="button" onclick="sayHello()">Say hello</button>
<script>
function sayHello() {
alert('Hello, Sam!');
}
</script> Or leave the HTML alone and hook the button up from your script:
<button type="button" id="hello-btn">Say hello</button>
<script>
document.getElementById('hello-btn').addEventListener('click', () => {
alert('Hello, Sam!');
});
</script>
To be fair to onclick: it works in every browser, it’s easy to read, and for a quick test it’s fine.
It gets awkward as a page grows, though:
- The function has to be global. Inside a module it isn’t, so the click does nothing but log an error.
-
An element has one
onclick. WithaddEventListeneryou can attach two separate things to the same click, say one that saves the form and one that shows “Saved”. - Your JavaScript ends up spread across the HTML, so it’s harder to find and change later.
-
Some sites send a security setting (a Content Security Policy) that blocks code in HTML attributes. On those,
onclickdoesn’t run at all.
More than one script, and libraries
Add one script tag per file. With defer they run in the order you wrote them, so put a library first
and the code that uses it after. Here the page loads Day.js, a small date library, from a CDN (a network of servers
that hands out files quickly), then your own file uses it:
<head>
<meta charset="utf-8">
<title>Today</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"
integrity="sha384-DpVxUeeBWjUvUV1czyIHJAjh+jYUZFu2lLakbdua5vbwOrBGi1UgaKCHjTC+x3Ky"
crossorigin="anonymous" defer></script>
<script src="script.js" defer></script>
</head>
<body>
<p id="today"></p>
</body> document.getElementById('today').textContent =
'Today is ' + dayjs().format('dddd, D MMMM');
The page shows something like “Today is Wednesday, 25 November”. Swap the two script tags around and you get
dayjs is not defined, because your code ran first.
-
integrityis a fingerprint of the exact file. If the file on the CDN ever changes, the browser refuses to run it. Copy the whole tag from the library’s own site or the CDN’s page instead of typing it out. - Keep a fixed version in the URL (
@1.11.13here), so an update can’t change your site overnight. - The file comes from another server, so the page needs an internet connection for it, even on your own computer.
When JavaScript is off: noscript
A few people browse with JavaScript turned off. Whatever you put in <noscript> only shows up
for them. It won’t help when your script fails to load or has an error, because JavaScript is still on.
You can see the message here because these boxes have scripts off. Paste the same code into a normal page with JavaScript on and only the price shows. Keep it for the few things that really need a script, and let the rest of the page work without one.
To style the page, how to link CSS to HTML works the same way, with a
<link> tag instead of <script>. And the
HTML Starter Template can build a blank page with both already in place.
Questions people ask
How do I link a JavaScript file to HTML?
Save your code in a file that ends in .js, for example script.js, and add <script src="script.js" defer></script> inside the <head> of your HTML page. If the file is in another folder, change the src to match, like src="js/script.js". Save both files and reload the page. The closing </script> tag is required, even with nothing between the tags.
Where should I put the script tag in HTML?
Either in the <head> with the defer attribute, or at the very end of the <body>, just before </body>. Both make sure the HTML is on the page before your code runs. A plain script tag in the head without defer runs before the body exists, so document.getElementById() finds nothing and you get a "Cannot read properties of null" error.
What is the difference between defer and async?
Both download the script while the page keeps loading. A defer script waits until all the HTML has been read and then runs, and several defer scripts run in the order you wrote them. An async script runs the moment it arrives, which can be before the HTML is finished, and async scripts can run in any order. Use defer for your own code, and async only for scripts that don’t depend on the page or on other scripts, like visitor stats.
Why is my JavaScript not working in HTML?
Open the browser’s Console first (F12 in most browsers, or Cmd+Option+J in Chrome on a Mac) and reload. The usual causes: the path in src is wrong, the file is really called script.js.txt, the script runs before the element it looks for exists (add defer), a syntax error stops the whole file, the script tag was self-closed as <script src="script.js" />, or the type attribute has a typo. A hard refresh (Ctrl+F5, or Cmd+Shift+R on a Mac) rules out an old cached copy.
Can I write JavaScript directly in an HTML file?
Yes. Put the code between <script> and </script> anywhere in the page, usually at the end of the body so the elements above it already exist. This is called an inline script. It only works on that one page, and if a tag has a src attribute, any code written between its tags is ignored, so use a separate script tag for inline code.
Do I need type="text/javascript" in the script tag?
No. JavaScript is the default, so <script src="script.js"></script> is enough. type="text/javascript" still works when it’s spelled right, but a typo in it (like text/javascipt) stops the script without any error, so it’s safer to leave it out. The one type worth writing today is type="module" for code that uses import and export.
Can I link more than one JavaScript file?
Yes, add one <script> tag per file. With defer on each, they run in the order the tags appear, so put a library first and the code that uses it after it. If your file runs before the library, the console says something like "dayjs is not defined".
Can a script tag be self-closing?
No. <script src="script.js" /> doesn’t work in HTML: the browser ignores the slash, so the tag stays open and everything after it, up to the next </script>, is swallowed. That HTML disappears from the page and the next script doesn’t load. Always write <script src="script.js"></script>.
Should I use onclick or addEventListener?
Both work. onclick="sayHello()" in the HTML is quick for a small test. addEventListener in a .js file keeps the code in one place, lets you attach more than one handler to the same click, and also works inside module scripts and on sites with a strict security policy, where onclick attributes can fail. For code you plan to keep, use addEventListener.
Keep going
Tools that help
- HTML Editor HTML, CSS and JS tabs with a Run button, so you can test a script right away.
- HTML Starter Template A blank page with script tags already set up, defer or module.
- HTML Validator Checks the HTML side of the page for mistakes.
- HTML Formatter Re-indents a messy page so you can spot a tag in the wrong place.
More tutorials
- How to Center Text, a Div or an Image in HTML & CSS
- How to Add a Line Break in HTML
- How to Add Spaces in HTML
- How to Change Text Color in HTML
- How to Change Background Color in HTML
- How to Add an Image in HTML
- What Is a URL? Meaning, Parts and Examples
- How to Redirect a Page in HTML
- How to Get an Image URL
- Canonical URL
- What Is HTML? What It Stands For and How It Works
- How to Create, Open and Run an HTML File
- How to Link CSS to HTML
- How to See the HTML Code of a Website
- HTML hr Tag
- HTML Comments
- How to Make Text Bold in HTML
- HTML Font and Font Size
- All tutorials