Skip to content

How to Link JavaScript to HTML

Short answer: save your JavaScript in its own file, say script.js, and add <script src="script.js" defer></script> inside the <head> of your HTML. defer makes the browser wait until the page is ready before it runs your code. You can also write JavaScript straight into the page between <script> tags. Both are below, plus what to check when nothing happens.

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.

index.html
<!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>
script.js
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 .js file holds only JavaScript. No <script> tags inside it, and no HTML.
  • defer is a yes/no attribute, so writing the word is enough. defer="true" works too, but so would defer="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:

  1. 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>
  2. Paste script.js from above into the JS tab.
  3. 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

One line in the head
<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

Code inside the page
<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:

coffee-counter.html, all in one file
<!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:

Runs too early
<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 + 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

Just before </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

script.js
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:

Four ways to load a script
<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
  • defer and async only work on tags with src (for classic scripts). On an inline <script> they’re ignored, and the code runs right where it is.
  • Order matters with async. If script.js uses a library and both are async, the library may not be there yet when your code runs. Use defer on 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>.

greet.js
export function greet(name) {
  return 'Hello, ' + name + '!';
}
main.js
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 plain defer scripts 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.

BrowserWindows / LinuxMac
Chrome, EdgeF12, or Ctrl+Shift+J for the ConsoleCmd+Option+J
FirefoxF12, or Ctrl+Shift+K for the ConsoleCmd+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:

  1. The path is wrong. src is a path from the HTML file to the .js file. A script in a js folder is src="js/script.js", and from a page in a subfolder it’s src="../js/script.js". Spelling counts: Script.js and script.js are different files on most web servers. The paths work the same as the ones for CSS, see the file path table.
  2. The file is really called script.js.txt. Notepad likes to add .txt, and TextEdit saves .rtf unless 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.
  3. The script runs before the element exists. The Cannot read properties of null error. Add defer or move the tag to the end of the body, as shown above.
  4. 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.
  5. 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 and prices.js never runs.
Self-closed (broken)
<h2>Coffee menu</h2>
<script src="menu.js" />
<p>Espresso, latte, mocha.</p>
<script src="prices.js"></script>
<p>Open 8 to 4.</p>
What you see

Coffee menu

Open 8 to 4.

Closed properly
<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>
What you see

Coffee menu

Espresso, latte, mocha.

Open 8 to 4.

  1. A typo in the tag. It’s src, not href or scr. And a misspelled type, like type="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).
  2. </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.
  3. 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.
  4. A module function isn’t found. Functions inside a type="module" script aren’t visible to the rest of the page, so onclick="sayHello()" fails with sayHello is not defined. Use addEventListener inside the module instead.

Do you need type="text/javascript"?

These two do the same thing
<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:

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:

addEventListener
<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. With addEventListener you 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, onclick doesn’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:

A library, then your own script
<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>
script.js
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.

  • integrity is 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.13 here), 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.

A noscript message

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