Modules in the Browser

Junior Year, page 3 of 11. A one-minute read.

To use modules in a web page, add type="module" to your script tag:

HTML
<script type="module" src="main.js"></script>

Module scripts behave a little differently from normal scripts:

  • They can use import and export.
  • Each module has its own scope, so top-level variables don't leak into the global scope.
  • They're deferred automatically: they wait for the HTML to finish loading before running, so you can put the tag in the <head> and still use document.querySelector.
  • They always run in strict mode, which turns some silent mistakes into loud errors. (Good!)
Watch outModules need a server

If you double-click your index.html file to open it, module scripts won't load, and you'll see a CORS error in the console. For security reasons, browsers only load modules from a web address (like http://localhost:5500), not directly from a file on your computer (file:///...). The easy fix: use the Live Server extension in VS Code (from Kindergarten). It runs a tiny web server on your computer, and modules work perfectly.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning