Lesson 5 of 5
The DOM, events and the browser
2 min read
Selecting and changing elements
const list = document.querySelector("#jobs");
const items = document.querySelectorAll(".job"); // static NodeList
const li = document.createElement("li");
li.textContent = "Frontend intern"; // safe: never parses HTML
list.append(li);Prefer textContent over innerHTML with user data: innerHTML can execute injected scripts (XSS).
Event propagation
Events travel in three phases: capture (window down to the target), target, then bubble (back up). Listeners run in the bubble phase by default.
e.stopPropagation()stops the event going further up.e.preventDefault()stops the browser's default action (following a link, submitting a form).
Event delegation
Attach one listener to a parent instead of one per child. It works for items added later and uses less memory.
document.querySelector("#jobs").addEventListener("click", (e) => {
const btn = e.target.closest("button[data-id]");
if (!btn) return;
apply(btn.dataset.id);
});Debounce vs throttle
- Debounce: run after the user stops for N ms (search box, resize end).
- Throttle: run at most once every N ms (scroll position, mouse move).
function throttle(fn, ms) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= ms) { last = now; fn(...args); }
};
}Storage
| Size | Lifetime | Sent to server? | |
|---|---|---|---|
| Cookies | ~4 KB | set by expiry | yes, with every request |
localStorage | ~5 MB | until cleared | no |
sessionStorage | ~5 MB | until the tab closes | no |
Never store secrets or auth tokens where page scripts can read them if you can use an HttpOnly cookie instead.
How a page loads (a favourite question)
- DNS lookup, TCP + TLS handshake, HTTP request.
- The browser parses HTML into the DOM and CSS into the CSSOM.
- Scripts block parsing unless marked
defer(run after parsing, in order) orasync(run when downloaded, any order). - DOM + CSSOM → render tree → layout (sizes and positions) → paint → composite.
Changing layout properties (width, top) triggers layout again (expensive); transform and opacity can be animated cheaply on the compositor.
Modules
ES modules (import / export) are the standard. Named exports vs default export; modules run in strict mode, have their own scope and are loaded once. CommonJS (require, module.exports) is the older Node system.
Check yourself
- What is event delegation and why is it useful?
defervsasyncon a script tag?- Why is
innerHTMLwith user input dangerous?
Sign up free to save your progress.