Sub topic 2
Running JavaScript in a Web Page
This chapter assumes you know basic HTML structure, can write simple JavaScript functions, and can run commands in a terminal. It covers how the browser finds, downloads, and runs your scripts, and how the attributes on a <script> tag change when your code runs.
How the HTML parser meets a script
The browser reads HTML from top to bottom and builds the document as it goes. When the parser reaches a <script> tag, it has to decide whether to stop and run the script or keep parsing. The tag's attributes decide this.
| Script kind | Blocks parsing? | Runs when | Order kept? |
|---|---|---|---|
| Classic `<script src>` | Yes, during download and execution | As soon as it downloads | Yes |
| `defer` | No | After parsing, before `DOMContentLoaded` | Yes |
| `async` | Only while it executes | As soon as it downloads | No |
| `type="module"` | No | After parsing, like `defer` | Yes |
| `type="module" async` | Only while it executes | As soon as it and its imports download | No |
Classic scripts
A classic script with no attributes blocks the parser. If it sits in the <head> and calls document.getElementById, the elements in <body> do not exist yet, so the call returns null. That is why older pages put scripts at the end of <body>.
defer and async
defer tells the browser to download the file while parsing continues, then run it once the document is fully parsed. Deferred scripts run in the order they appear, so a library and the code that uses it can both be deferred safely.
async also downloads in parallel, but the script runs the moment it arrives. Two async scripts can run in either order. Use async for independent scripts, such as analytics, that touch nothing else on the page.
Both attributes only apply to external scripts with src. On an inline classic script they are ignored.
Module scripts
A module script is deferred by default, so main.js below runs after the document is parsed even though the tag sits in the head.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
<script type="module" src="main.js"></script>
</head>
<body>
<p id="out"></p>
</body>
</html>// main.js
const out = document.getElementById('out');
out.textContent = `Running in ${navigator.userAgent}`;Modules also behave differently from classic scripts in several ways:
- They always run in strict mode.
- Top-level variables belong to the module. They do not become properties of
window. - They can use
importandexport, and top-levelawait. - They are fetched with CORS rules, so they fail to load from
file://URLs. - Each module runs only once, however many times it is imported.
Common errors
nullfrom a DOM lookup: a classic script ran before the element was parsed. Adddeferor use a module.- Dependency undefined: two
asyncscripts ran out of order. Switch both todefer. - Module not loading: the page was opened over
file://, or the server sends a non-JavaScript MIME type. - Global not found: code expects a top-level
letin a module to be visible from another script. Export it and import it instead.
Exercise
A page has, in its head, <script async src="a.js">, <script defer src="b.js">, and <script type="module" src="c.js">, in that order. Which scripts are guaranteed to run after the document is parsed, and in what order relative to each other?
Show answer
b.js and c.js are both guaranteed to run after parsing, and b.js runs before c.js because deferred scripts and modules run in document order. a.js runs whenever it finishes downloading, which could be before parsing ends or between the others.
Exercise
A classic script in the head runs document.querySelector('button').addEventListener('click', go) and throws "Cannot read properties of null". Give two fixes.
Show answer
Add the defer attribute to the script tag, or change it to type="module". Both make it run after the button has been parsed. Moving the script to the end of the body also works.