🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Modules in the Browser

A module script is a script tag with type module. The browser waits for the page to load before it runs such a script.

The page is ready when the script runs

This classic script sits at the end of the body. It can already read the heading, which proves the page was parsed first.

console.log(document.querySelector("h1").textContent);

Strict mode is always on in modules

Module scripts run in strict mode. This classic script turns strict mode on by hand, and writing to a name that was never declared throws a ReferenceError.

"use strict";
try {
  total = 5;
} catch (err) {
  console.log(err.name);
}

A script element can carry the module type

A script element takes a type of module. The type is read back from the element itself.

const script = document.createElement("script");
script.type = "module";
console.log(script.type);

Example

document.getElementById("demo").textContent = "The page was ready first.";
console.log(document.getElementById("demo").textContent);
console.log(document.querySelector("h1").textContent);

Key points

  • Module script: a script tag with type set to module
  • Deferred: run after the page has loaded, not while it loads
  • A classic script at the end of the body also runs after the page is parsed.
  • Module scripts always run in strict mode, which forbids some sloppy habits.
  • A module script can use import and export, and a classic script cannot.

In this example, the script writes into the demo paragraph and reads the text back. It also reads the page heading. Both reads work, because a script at the end of the body runs after the page is parsed.

Note

Opening a page straight from a file address breaks module loading. Run the page through a web server instead.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

When does a module script run?