HTML with Modern JavaScript
By the end of this lesson you will be able to load your code as ES modules with clean import names, fetch JSON from an API and turn it into HTML without opening an XSS hole, cancel slow requests and copy data safely before editing it.
What you should know first: HTML Integration with JavaScript for script loading and textContent, and Advanced DOM Integration for building nodes. The JavaScript course explains the language side in Modules, async & await and Fetch API. Here we focus on how that code meets your HTML.
ES modules in the browser
An ES module is a JavaScript file that shares code with export and uses other files' code with import. You load one with type="module":
<script type="module" src="js/app.js"></script>// js/app.js
import { withGst } from "./gst.js";
console.log(withGst(1000));Think of modules as separate departments in a school office. Each keeps its own files, and you get something only by asking for it by name. A module script behaves differently from a classic script:
| Behaviour | Classic <script> | <script type="module"> |
|---|---|---|
| Timing | Blocks parsing unless defer or async | Deferred automatically |
| Top-level variables | Become globals on window | Stay private to the module |
| Strict mode | Only with "use strict" | Always on |
import / export | Not allowed | Allowed |
| Same file included twice | Runs twice | Runs once |
Top-level await | Not allowed | Allowed |
Module files from another origin need CORS headers, and Chrome blocks module files when you open the page by double-clicking it (a file:// address). Serve your project from a local server such as XAMPP's http://localhost instead.
Import maps: short names for long paths
A bare specifier is an import name with no path, such as import { format } from "rupee". Browsers cannot guess where "rupee" lives, so on its own it throws an error. An import map tells them:
<script type="importmap">
{
"imports": {
"rupee": "/js/vendor/rupee.js",
"components/": "/js/components/"
}
}
</script>
<script type="module" src="/js/app.js"></script>Now import "rupee" loads /js/vendor/rupee.js, and a key ending in / maps a whole folder, so "components/card.js" becomes /js/components/card.js. The map must be valid JSON and must come before the first module script. Import maps are Baseline 2023. It works like a phone's contact list: you tap "Amma" and the phone dials the full number.
Import maps let you skip a build tool on small sites. Large apps still use a bundler such as Vite to combine and shrink files.
Step 1: a module, an import map and top-level await
This example maps the name "gst" to a tiny module written as a data: URL, so it runs inside the editor without extra files. In a real project the URL would be a file path.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Modules and import maps</title>
<script type="importmap">
{
"imports": {
"gst": "data:text/javascript,export const withGst = (amount, rate = 18) => amount + amount * rate / 100; export const rupees = (n) => new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(n);"
}
}
</script>
</head>
<body>
<h1>Meera Stores price list</h1>
<ul id="prices"></ul>
<pre id="log"></pre>
<script type="module">
import { withGst, rupees } from "gst";
const log = (line) => (document.querySelector("#log").textContent += line + "\n");
const items = await Promise.resolve([["Pressure cooker", 1999], ["Steel tiffin", 450]]);
for (const [name, price] of items) {
const li = document.createElement("li");
li.textContent = `${name}: ${rupees(withGst(price))} with GST`;
document.querySelector("#prices").append(li);
}
log("typeof window.withGst: " + typeof window.withGst);
log("this at top level: " + this);
</script>
<script>
document.querySelector("#log").textContent += "Classic script ran first\n";
</script>
</body>
</html>Pressure cooker: ₹2,358.82 with GST Steel tiffin: ₹531.00 with GST Classic script ran first typeof window.withGst: undefined this at top level: undefined
The classic script comes later in the file but runs first, because modules are deferred. withGst is not a global, and this is undefined at the top of a module. The await sits outside any function, which is top-level await. It works only in modules (Baseline 2021), and it pauses this module and any module that imports it, so avoid slow awaits at the top of shared modules.
Fetching JSON and rendering it safely
The usual pattern has five parts. Show a loading message, await fetch(), check response.ok, read the JSON, then build elements with textContent.
Two modern operators keep the rendering code short. Optional chaining user.address?.city returns undefined instead of throwing when address is missing. Nullish coalescing value ?? "fallback" uses the fallback only for null or undefined, so a real 0 or an empty string survives.
An AbortController cancels a request. You pass its signal to fetch(). Calling controller.abort() makes the fetch promise reject with an AbortError. AbortSignal.timeout(ms) gives a signal that aborts by itself with a TimeoutError, and AbortSignal.any([...]) combines several signals (Baseline 2024).
Step 2: a user directory with cancel and timeout
Rohan's team directory comes from the test API at jsonplaceholder.typicode.com. The module loads it at top level, and the buttons reload or cancel.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Team directory</title>
<style>
.card { border: 1px solid #ccc; border-radius: 8px; padding: 8px 12px; margin: 6px 0; }
.error { color: #b71c1c; }
</style>
</head>
<body>
<h1>Team directory</h1>
<button id="reload" type="button">Reload</button>
<button id="cancel" type="button">Cancel</button>
<p id="status" role="status"></p>
<div id="people"></div>
<script type="module">
const status = document.querySelector("#status");
const people = document.querySelector("#people");
let controller;
function card(user) {
const div = document.createElement("div");
div.className = "card";
const h2 = document.createElement("h2");
h2.textContent = user.name;
const p = document.createElement("p");
p.textContent = `${user.email}, ${user.address?.city ?? "city not given"}, works at ${user.company?.name ?? "unknown"}`;
div.append(h2, p);
return div;
}
async function loadUsers() {
controller?.abort(); // cancel any earlier request
controller = new AbortController();
const mine = controller;
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(8000)]);
status.className = "";
status.textContent = "Loading...";
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users?_limit=3", { signal });
if (!response.ok) throw new Error(`Server replied ${response.status}`);
const users = await response.json();
people.replaceChildren(...users.map(card));
status.textContent = `Loaded ${users.length} people.`;
} catch (err) {
if (mine !== controller && err.name === "AbortError") return; // a newer request replaced this one
status.className = "error";
if (err.name === "AbortError") status.textContent = "Request cancelled.";
else if (err.name === "TimeoutError") status.textContent = "The server is too slow. Try again.";
else status.textContent = `Could not load the directory (${err.message}).`;
}
}
document.querySelector("#reload").addEventListener("click", loadUsers);
document.querySelector("#cancel").addEventListener("click", () => controller?.abort());
await loadUsers();
</script>
</body>
</html>You should see "Loaded 3 people." and cards for Leanne Graham, Ervin Howell and Clementine Bauch. Press Reload and then Cancel quickly: the status says "Request cancelled." and the old cards stay. Press Reload twice quickly: the first request is aborted silently, because the mine check sees that a newer request has replaced it. fetch rejects only for network failures and aborts, not for a 404 or 500, which is why the code checks response.ok itself.
Template literals or DOM building?
Template literals (backtick strings with ${}) make it tempting to set list.innerHTML to a string such as <li>${comment.text}</li>. It reads nicely, but the browser parses the result as HTML. If the data contains markup, that markup becomes real elements, and an attribute such as onerror runs code. This is cross-site scripting (XSS), and API data is not safe just because it comes from your own server: users typed it.
Step 3: see the difference on your own page
The second comment below contains an image tag with an onerror handler. It only reveals a hidden warning on this page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Template literal vs DOM</title>
<style>#alarm { background: #ffebee; color: #b71c1c; padding: 8px; }</style>
</head>
<body>
<p id="alarm" hidden>Injected code just ran on this page.</p>
<h2>Unsafe: innerHTML with a template literal</h2>
<ul id="unsafe"></ul>
<h2>Safe: createElement and textContent</h2>
<ul id="safe"></ul>
<script>
const comments = [
{ name: "Priya", text: "Great filter coffee at Kochi station!" },
{ name: "Visitor", text: '<img src="data:," onerror="document.querySelector(\'#alarm\').hidden = false">Nice!' }
];
document.querySelector("#unsafe").innerHTML = comments
.map((c) => `<li><b>${c.name}</b>: ${c.text}</li>`)
.join("");
for (const c of comments) {
const li = document.createElement("li");
const b = document.createElement("b");
b.textContent = c.name;
li.append(b, `: ${c.text}`);
document.querySelector("#safe").append(li);
}
</script>
</body>
</html>The warning appears because the unsafe list ran the handler. The safe list shows the tag as plain characters. Template literals are still perfect for building text, as in the li.append() call of the safe loop. The danger is only in handing the result to an HTML parser. If you must build markup from a string, escape the data first; Safe DOM Manipulation and Trusted Types Fundamentals go further.
structuredClone: a true deep copy
Before letting a user edit a cart or a form draft, you often want a copy, so Cancel can restore the original. { ...cart } copies only the top level; nested objects are still shared. structuredClone() (Baseline 2022) copies everything, including Date, Map and Set values.
const cart = {
customer: "Meera",
placedOn: new Date("2026-11-15T10:30:00+05:30"),
items: new Map([["Idli", 2], ["Dosa", 1]])
};
const draft = structuredClone(cart);
draft.items.set("Vada", 3);
console.log(cart.items.size, draft.items.size);
console.log(draft.placedOn instanceof Date);
const viaJson = JSON.parse(JSON.stringify(cart));
console.log(typeof viaJson.placedOn, viaJson.items);
try {
structuredClone({ onSave() {} });
} catch (err) {
console.log(err.name);
}2 3
true
string {}
DataCloneErrorThe old JSON trick turns dates into strings and empties the Map. structuredClone cannot copy functions or DOM nodes; it throws a DataCloneError. Class instances come back as plain objects without their methods.
Common mistakes
- Opening module pages from
file://. Use a local server. - Expecting module variables on
window. Export them, or attach deliberately. - Forgetting
response.ok. A 404 still resolves thefetchpromise. innerHTMLwith template literals and API data. Build nodes, or escape every value.- Using
||for defaults.0 || 10gives 10;0 ?? 10keeps 0. - Never cancelling. Old requests can finish after new ones and overwrite fresh results.
Interview questions
1. How is a module script different from a classic script?
It is deferred by default, always in strict mode, and its top-level variables stay private instead of becoming globals. It can use import, export and top-level await, and the same module URL runs only once per page.
2. What problem does an import map solve?
Browsers cannot resolve bare specifiers such as "lodash-es". An import map is a JSON block in <script type="importmap"> that maps those names, or folder prefixes, to real URLs. It must appear before the module scripts that use it.
3. Does fetch reject on a 404?
No. It rejects only for network errors or an abort. A 404 or 500 resolves normally, so you check response.ok or response.status and throw your own error.
4. Why is innerHTML with a template literal risky?
The finished string is parsed as HTML, so any markup in the data becomes real elements and event-handler attributes can run code. Building elements and setting textContent keeps data as text.
5. How do you cancel a fetch request?
Create an AbortController, pass controller.signal in the fetch options and call controller.abort(). The promise rejects with an AbortError. AbortSignal.timeout() gives a self-aborting signal for timeouts.
6. When would you use structuredClone instead of spread?
When the object has nested data you plan to change. Spread copies only the top level, while structuredClone makes a deep copy and keeps Date, Map and Set values intact. It throws on functions and DOM nodes.
Key points
type="module"scripts are deferred, private in scope, strict and run once; serve them over HTTP.- An import map maps bare names and folder prefixes to URLs; put it before the first module script.
- Top-level
awaitworks only in modules and pauses the modules that import it. - Fetch pattern: loading state,
await fetch, checkresponse.ok,await response.json(), build nodes. - Template literals are fine for text; never pass data-filled strings to
innerHTML. AbortControllerandAbortSignal.timeout()cancel requests;structuredClonemakes deep copies.
Exercise
Build a "Class 10 to-do board" page as a module. Fetch https://jsonplaceholder.typicode.com/todos?userId=1&_limit=8 with a 5-second timeout. Show "Loading..." first, then two lists, "Done" and "Pending", built with createElement and textContent. Use Object.groupBy to split the todos by their completed value. Show a friendly error message for a timeout and a different one for any other failure.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>To-do board</title>
</head>
<body>
<h1>Class 10 to-do board</h1>
<p id="status" role="status">Loading...</p>
<h2>Done</h2><ul id="done"></ul>
<h2>Pending</h2><ul id="pending"></ul>
<script type="module">
const status = document.querySelector("#status");
const item = (todo) => {
const li = document.createElement("li");
li.textContent = todo.title;
return li;
};
try {
const response = await fetch("https://jsonplaceholder.typicode.com/todos?userId=1&_limit=8",
{ signal: AbortSignal.timeout(5000) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const todos = await response.json();
const groups = Object.groupBy(todos, (t) => (t.completed ? "done" : "pending"));
document.querySelector("#done").replaceChildren(...(groups.done ?? []).map(item));
document.querySelector("#pending").replaceChildren(...(groups.pending ?? []).map(item));
status.textContent = `${todos.length} tasks loaded.`;
} catch (err) {
status.textContent = err.name === "TimeoutError"
? "The server took too long. Please try again."
: `Something went wrong (${err.message}).`;
}
</script>
</body>
</html>Object.groupBy (ES2024) returns an object whose keys are the strings the callback returns; a group with no items is missing, so ?? [] guards it. Top-level await works because the script is a module.
Quick Quiz
1. A module declares const shop = "Meera Stores" at the top level. What is window.shop?
Top-level variables in a module stay private to that module.
2. fetch() gets a 404 response. What happens to the promise?
Only network failures and aborts reject; HTTP error codes still resolve.
3. Where must an import map appear?
The browser needs the map before it resolves any module import.
4. What does structuredClone do with a Date property?
Structured cloning supports Date, Map, Set and more; only functions and DOM nodes fail.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
