Sub topic 2
Running JavaScript in a Web Page
This chapter assumes you can read basic HTML and JavaScript, and that you can run a command in a terminal to start a local web server. Here you will learn how the browser finds <script> elements, when it fetches and runs them, and how the defer, async, and type="module" attributes change that timing. The DOM APIs themselves and the full module syntax get their own chapters. This one covers loading and execution order.
How the HTML parser meets a script
When a browser receives an HTML page, its parser reads the markup from top to bottom and builds the DOM (Document Object Model), the tree of objects that represents the page. A <script> element interrupts that process. What happens next depends on the script's attributes.
A classic script is a <script> with no type attribute, or with type="text/javascript". When the parser reaches a classic script, it stops building the DOM. If the script is external (it has src), the browser downloads the file, runs it, and only then goes back to parsing. This is called parser-blocking behavior.
Two problems follow from it:
- Code in a classic script can only see the elements parsed before it. Elements further down the page do not exist yet.
- A slow download in the
<head>delays everything after it, so the user sees a blank page longer.
Here is the first problem in action:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Too early</title>
<script>
// Runs before <body> is parsed, so the element does not exist yet.
const el = document.getElementById('out');
console.log(el); // null
</script>
</head>
<body>
<p id="out">Hello</p>
</body>
</html>A common fix used to be moving every <script> to just before </body>. That works, but the browser cannot start downloading the script until the parser has read almost the whole page. The attributes below solve both problems.
The four loading modes
Classic (blocking)
<script src="app.js"></script>The parser stops, app.js is fetched and run, then parsing continues. Classic scripts run in the order they appear. Top-level var and function declarations become properties of the global object, and every classic script on the page shares one global scope.
defer
<script defer src="app.js"></script>The browser fetches app.js in parallel with parsing and does not run it until the whole document has been parsed. Deferred scripts run in document order, after parsing and just before the DOMContentLoaded event fires. Use defer when your code touches the DOM or depends on another script.
async
<script async src="analytics.js"></script>The file is fetched in parallel, and it runs as soon as it arrives. That may happen before parsing finishes, and parsing pauses while the script runs. When several async scripts are on a page, their order follows which one finishes downloading first, so it is unpredictable. Use async for independent scripts that nothing else depends on, such as analytics or ads.
module
<script type="module" src="main.js"></script>Module scripts are deferred by default: they are fetched in parallel, along with everything they import, and they run after parsing in document order. You can add async to a module script so it runs as soon as it and its dependencies are ready.
Module scripts also behave differently in other ways:
- They always run in strict mode.
- Top-level variables belong to the module, not to the global object.
let x = 1in a module does not createwindow.x. - Each module runs only once, even if the page includes or imports it several times.
- They are fetched with CORS (Cross-Origin Resource Sharing), so a module from another origin must be served with a suitable
Access-Control-Allow-Originheader. - The server must send them with a JavaScript MIME type such as
text/javascript. document.currentScriptisnullinside a module. Useimport.meta.urlto find the module's own address.
Comparison table
| Script tag | Blocks parsing during fetch | Runs when | Order guaranteed | Global scope shared |
|---|---|---|---|---|
| `<script src>` | Yes | Immediately after fetch | Yes | Yes |
| `<script defer src>` | No | After parsing, before `DOMContentLoaded` | Yes | Yes |
| `<script async src>` | No | As soon as fetched | No | Yes |
| `<script type="module">` | No | After parsing, before `DOMContentLoaded` | Yes | No (module scope) |
| `<script type="module" async>` | No | As soon as it and its imports are ready | No | No (module scope) |
Inline scripts
An inline script has its code between the tags and no src. The rules differ slightly:
- An inline classic script always runs immediately. The
deferandasyncattributes are ignored on it. - An inline module script (
<script type="module">with code inside) is still deferred, andasyncdoes work on it.
Seeing the order for yourself
Create these four files in one folder. Each script logs a message so you can watch the order in the console.
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Script order</title>
<script>console.log('A: inline classic in head');</script>
<script defer src="deferred.js"></script>
<script type="module" src="module.js"></script>
<script async src="async.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
console.log('E: DOMContentLoaded');
});
window.addEventListener('load', () => {
console.log('F: load');
});
</script>
</head>
<body>
<p id="out">Waiting...</p>
<script>console.log('B: inline classic at end of body');</script>
</body>
</html>// deferred.js
console.log('C: defer, out element is', document.getElementById('out'));// module.js
console.log('D: module, strict mode is', this === undefined);
document.getElementById('out').textContent = 'Modules ran.';// async.js
console.log('async: ran whenever it finished downloading');Serve the folder over HTTP. Either command works:
npx serve .
# or
python3 -m http.server 8000Open the page and check the console. A and B always come first, then C, then D, then E, then F. The async line can show up anywhere before F, and it moves between reloads depending on caching and network timing. In deferred.js the #out element exists, which shows that deferred code sees the complete DOM. In module.js, this at the top level is undefined because modules run in strict mode with their own scope.
Scripts added from JavaScript
You can also create a script element in code:
const s = document.createElement('script');
s.src = 'extra.js';
document.head.append(s);A script inserted this way does not block parsing and behaves as if it were async. If you insert several scripts and need them to run in order, set s.async = false on each one before inserting it. The browser then runs them in insertion order. For loading code on demand, the dynamic import() expression is usually a cleaner choice, and the modules chapter covers it.
Supporting old browsers with nomodule
Browsers that understand modules skip any script that has the nomodule attribute. Browsers that do not understand modules ignore type="module" and run the nomodule script. This lets you ship a fallback bundle:
<script type="module" src="app.modern.js"></script>
<script nomodule defer src="app.legacy.js"></script>Every current browser supports modules, so you only need this pattern if you have to support very old browsers.
Common errors and what they mean
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot read properties of null` from `getElementById` | Classic script ran before the element was parsed | Use `defer` or `type="module"` |
| `SyntaxError: Cannot use import statement outside a module` | File uses `import` but was loaded as a classic script | Add `type="module"` to the tag |
| CORS error when opening `index.html` by double-clicking | Module scripts cannot load from `file://` URLs | Serve the folder over HTTP |
| "Failed to load module script... MIME type" | Server sends `.js` as `text/plain` or `text/html`, often a 404 page | Fix server config or the path |
| A variable from one module is `undefined` in another script | Module top-level bindings are not global | `export` it and `import` it, or assign to `globalThis` on purpose |
| Scripts with `async` break randomly | One async script depends on another | Use `defer` to keep document order |
Exercises
Exercise
A page has <script async src="lib.js"></script> followed by <script async src="app.js"></script>, and app.js calls a function defined in lib.js. It works on your machine but sometimes fails in production. Why, and what is the smallest fix?
Show answer
Async scripts run as soon as each one finishes downloading, so app.js can run before lib.js when lib.js downloads more slowly. Replace async with defer on both tags. Deferred scripts still download in parallel but run in document order, so lib.js always runs first.
Exercise
Inside <script type="module"> you write let count = 0;. A later classic inline script logs window.count. What does it print, and why?
Show answer
It prints undefined. Top-level declarations in a module are scoped to that module and are not added to the global object. Even a top-level var in a module would not create window.count.
Exercise
You add <script defer>console.log(document.body);</script> (inline, no src) inside <head>. What is logged?
Show answer
null. The defer attribute is ignored on inline classic scripts, so the code runs immediately, before the parser has created the body element.
Exercise
You open index.html straight from disk, and the console shows a CORS error for main.js, which is loaded with type="module". The same file works on your colleague's machine when run through npx serve. Explain the difference.
Show answer
Module scripts are fetched in CORS mode, and browsers do not treat file:// URLs as a valid origin for those requests, so the fetch is blocked. Serving over HTTP gives the page a real origin (for example http://localhost:3000), and same-origin module requests succeed.