JavaScript in the Browser: Scripts, Modules, defer, async and the Page Lifecycle
How JavaScript runs in a web page: script elements, defer, async and type="module" compared, where to put scripts, window and the global scope, DOMContentLoaded, load, pagehide and visibilitychange, the single-threaded rendering model, and the browser security basics every developer needs.
kvi5hnuCode Sprout team member10 min readOn this page
Part 15 moves from the language to its most famous home: the web browser. Here JavaScript works with the document (the DOM), reacts to events, talks to servers, stores data and draws graphics. All of these come from web APIs that the browser provides, not from the ECMAScript standard. This article covers the foundation: how scripts get into a page, when they run, and the page lifecycle around them.
Browser code doesn't run in Node, so most examples in this part are shown without output. Paste them into the DevTools console of any page (article 2), or into a small HTML file, to try them.
Adding JavaScript to a page
<!-- external file: the usual choice -->
<script src="/js/app.js" defer></script>
<!-- an ES module, which can use import/export -->
<script type="module" src="/js/main.js"></script>
<!-- inline code (fine for tiny snippets) -->
<script>
document.documentElement.classList.add("js-enabled");
</script>
External files can be cached by the browser and shared between pages, and they keep markup and logic separate. Avoid inline event handler attributes like onclick="...": they mix concerns, run in a strange scope, and are blocked by a strict Content Security Policy (see below).
When scripts run: classic, defer, async and module
The browser builds the page by parsing the HTML from top to bottom. What happens when the parser reaches a <script> depends on its attributes:

| Script | Blocks parsing? | Runs | Order between scripts |
|---|---|---|---|
<script src> (classic) | yes, while downloading and running | immediately | document order |
<script defer src> | no | after parsing, before DOMContentLoaded | document order |
<script async src> | only while running | as soon as downloaded | whichever arrives first |
<script type="module"> | no (deferred by default) | after parsing | document order |
<script type="module" async> | only while running | as soon as it and its imports are ready | whichever is ready first |
Practical guidance:
- Use
type="module"for application code (modern syntax,import, strict mode, deferred automatically) ordeferfor classic scripts. Both let you put the tag in<head>, so downloading starts early, while still running after the DOM is built. - Use
asyncfor independent scripts that don't touch your other code and don't care about order, such as analytics. - A plain classic
<script>in<head>delays rendering until it downloads and runs. That's why older advice was to put scripts at the end of<body>;deferand modules make that unnecessary. deferandasynconly apply to external scripts (src). Inline module scripts are deferred too.
Module scripts differ from classic ones in a few more ways (article 75): they run in strict mode, have their own top-level scope (their variables don't become globals), run only once even if included twice, use CORS for cross-origin files, and support top-level await.
You can also add scripts dynamically, for example to load a feature only when needed. Dynamic import() is usually simpler:
button.addEventListener("click", async () => {
const { openEditor } = await import("./editor.js"); // downloaded on first click
openEditor();
});
The window object and the global scope
In a browser, the global object is window (also reachable as globalThis, self and frames). It holds the whole browser API: document, location, history, navigator, localStorage, fetch, setTimeout, console and more.
console.log(window === globalThis); // true
console.log(window.innerWidth, location.href, navigator.language);
In classic scripts, top-level var declarations and function declarations become properties of window, and all classic scripts on the page share one global scope. That's why old libraries polluted globals and collided with each other. Top-level let, const and class are shared between classic scripts too, but they don't become window properties: another script can call new Cart(), but not new window.Cart(). Modules don't share their top-level declarations at all; they export what others may use. Another quirk: elements with an id are exposed as global variables (<div id="menu"> creates window.menu). Never rely on it; use document.getElementById.
Each <iframe> has its own window, its own document and its own set of built-ins, so it's effectively a separate program. Frames from the same origin can reach into each other (iframe.contentWindow); cross-origin frames can only exchange messages with postMessage (article 120). This is also why instanceof Array can fail for an array created in another frame, while Array.isArray works.
A page's program runs in two phases
There's no single "main" function in a web page. Instead, a page's JavaScript runs in two phases:
- Loading. The browser parses the HTML and runs scripts as described above. A classic script without
deferorasyncsees only the part of the document that precedes it. When parsing ends,document.readyStatebecomes"interactive", deferred and module scripts run, andDOMContentLoadedfires. Someasyncscripts may still be pending at this point. - Event-driven. From then on, code runs only in response to events: clicks, key presses, timers, network responses, messages. Whatever the loading phase registered (event listeners, timers, observers) is what keeps the program alive. After all resources and async scripts are done,
readyStatebecomes"complete"andloadfires onwindow.
Most of a page's lifetime is spent idle in phase 2, waking up briefly for each event.
Input and output
A browser program gets its input from:
- the document itself, through the DOM (articles 109 and 110);
- user events such as clicks, typing and form input (article 108);
- the URL:
new URL(location.href)exposes the path, query parameters and fragment (article 88); - cookies (
document.cookie) and other storage (article 119); - the environment:
navigator.language,navigator.hardwareConcurrency(CPU cores),navigator.onLine,screen.width, andmatchMedia("(prefers-color-scheme: dark)"), which are the browser's equivalent of a Node program's environment variables.
Its output is usually changes to the document. console.log output only reaches the developer tools, so it's for debugging, not for users.
Handling errors globally
An uncaught exception in a browser doesn't crash anything: the browser logs it in the console, abandons that task, and keeps handling other events. That makes errors easy to miss, so production sites collect them with two global events:
window.addEventListener("error", (event) => {
// uncaught exceptions; event.error is the thrown value, with filename/lineno/colno
reportError({ message: event.message, stack: event.error?.stack });
});
window.addEventListener("unhandledrejection", (event) => {
// rejected promises with no handler (article 96)
reportError({ message: String(event.reason) });
});
(reportError here stands for your own function that sends the data to a monitoring service.) Errors from scripts loaded from other origins show only "Script error." unless the script is served with CORS headers and loaded with crossorigin.
The page lifecycle
A page goes through several stages, each signaled by an event:
| Event | Fired on | When |
|---|---|---|
DOMContentLoaded | document | HTML fully parsed and deferred/module scripts run; images may still be loading |
load | window | everything loaded, including images, stylesheets and iframes |
visibilitychange | document | the tab is hidden or shown (document.visibilityState is "hidden" or "visible") |
pagehide / pageshow | window | the user navigates away / back (including from the back/forward cache) |
beforeunload | window | the page is about to unload; can ask the user to confirm leaving |
document.addEventListener("DOMContentLoaded", () => {
// safe to query and change the DOM (not needed in module or defer scripts)
});
window.addEventListener("load", () => {
// images are loaded: safe to measure their sizes
});
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
navigator.sendBeacon("/analytics", JSON.stringify(sessionStats)); // reliable last chance to send data
}
});
document.readyState tells you which stage you're in: "loading", "interactive" (parsed, so DOMContentLoaded is about to fire) or "complete" (load fired). A script that may run either before or after parsing can check it:
function onReady(fn) {
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", fn);
else fn();
}
Modern guidance: don't use the unload event. It's unreliable on mobile, and it prevents the page from entering the back/forward cache (bfcache), which makes back-button navigation instant. Save state on visibilitychange (hidden) or pagehide instead, and use beforeunload only while there are genuinely unsaved changes.
One thread for scripts and rendering
Everything from article 94 applies here, with the browser's rendering added to the event loop. The same main thread runs your JavaScript, handles input, and calculates layout and paints the page. While a script runs, the page can't repaint or respond. A long task (over about 50 ms) makes the page feel janky, and the Interaction to Next Paint (INP) metric used by search engines measures exactly this.
- Keep event handlers short; split long work into chunks (
await scheduler.yield()where available, orsetTimeout), or move it to a Web Worker (article 120). - Use
requestAnimationFrame(callback)for visual updates. It runs the callback just before the next paint, synchronized with the display's refresh rate.
function animate(timestamp) {
box.style.transform = `translateX(${(timestamp / 10) % 300}px)`;
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Security basics
Browsers run code from any website you visit, so the platform restricts what scripts can do:
- Sandboxing. Scripts can't read your files or run programs. Access to the camera, location, notifications and clipboard requires user permission.
- The same-origin policy. An origin is the scheme, host and port (
https://shop.example:443). Scripts can freely read data only from their own origin. Reading responses from other origins requires the server's permission through CORS headers (article 116). Iframes and windows from other origins are isolated from each other. - Cross-site scripting (XSS) is the main threat you create yourself: inserting untrusted text as HTML (
element.innerHTML = userInput) lets attackers run scripts in your page. UsetextContentfor text (article 110) and sanitize any HTML you must insert. - Content Security Policy (CSP) is an HTTP header that limits where scripts may come from, such as
script-src 'self'. It blocks injected inline scripts andeval, which makes XSS much harder. - Subresource Integrity (
<script src="..." integrity="sha384-...">) makes the browser refuse a CDN file whose contents changed.
Common questions
Should I use defer or type="module"?
For new code, type="module": it's deferred automatically and gives you import, strict mode and module scope. Use defer for classic scripts that aren't modules.
Do I still need DOMContentLoaded?
Not in module or defer scripts, which run after parsing. It's still useful in async scripts, or classic scripts placed in <head> without defer.
What's the difference between DOMContentLoaded and load?
DOMContentLoaded fires once the HTML is parsed and the DOM is ready. load waits for images, stylesheets, iframes and other resources as well, which can take much longer.
Why is my global variable missing in another script?
If either script is a module, top-level variables are module-scoped, not global. Export and import what you need (or, as a last resort, assign to window explicitly).
Summary
- Scripts load as classic (blocking),
defer(after parsing, in order),async(as soon as ready, any order) ortype="module"(deferred, module scope). - Prefer modules or
deferin<head>; useasyncfor independent scripts. windowis the browser's global object; classic scripts share one global scope, while modules don't create globals.- Lifecycle events:
DOMContentLoaded,load,visibilitychange,pagehide/pageshowandbeforeunload; avoidunload. - One main thread runs scripts and rendering: keep tasks short and use
requestAnimationFramefor animation. - The same-origin policy, CORS, CSP and avoiding
innerHTMLwith untrusted data are the security basics.
Practice Questions
In what order do these log, assuming a.js downloads slowly and b.js quickly?
<script defer src="a.js"></script> <!-- logs "a" -->
<script defer src="b.js"></script> <!-- logs "b" -->
Answer
a then b. Deferred scripts always run in document order after parsing, regardless of which download finishes first. With async, b would probably log first.
A classic script in <head> runs document.querySelector("#app").textContent = "Hi" and throws. Why, and what are two fixes?
Answer
The script runs before the parser has reached #app, so querySelector returns null. Fix it by adding defer (or using type="module"), or by running the code in a DOMContentLoaded listener.
You need to save a draft when the user leaves the page. Which event should you use, and why not unload?
Answer
Use visibilitychange when document.visibilityState is "hidden" (or pagehide). It fires reliably, including on mobile when the app is backgrounded. unload often doesn't fire on mobile, and it disables the back/forward cache.
Is https://example.com the same origin as https://api.example.com? As http://example.com?
Answer
Neither. The host differs in the first case and the scheme differs in the second. An origin is scheme, host and port together.
Previous: JavaScript Proxy Patterns and Pitfalls: Reactivity, Negative Indexes, Invariants and Limits
Next: JavaScript Events: addEventListener, the Event Object, Bubbling, Capturing and Delegation

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.