Sub topic 13
Fetching CSS, scripts, images and fonts
This chapter assumes you know how a browser receives an HTML response (the previous chapters covered DNS, TCP, TLS and HTTP) and that you can read basic HTML and CSS. It covers the step between "the HTML has arrived" and "the page can be drawn". During that step the browser finds more files to download and decides how each one affects parsing and rendering.
What a subresource is
The HTML response is the main resource. Every other file the page needs is a subresource: stylesheets, scripts, images, fonts, videos, and data requested by scripts with fetch. Each subresource is a separate HTTP request. It goes through the same cache check, DNS lookup, connection and HTTP exchange you have already seen, except that the browser often reuses an open connection to the same host.
Here is the page from this tutorial's running example:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="/style.css">
<script src="/app.js" defer></script>
</head>
<body>
<h1>Hello</h1>
<img src="/logo.png" alt="Logo">
</body>
</html>One HTML file produces three more requests: /style.css, /app.js and /logo.png. A fourth request may follow if style.css refers to a font.
How the browser discovers subresources
The HTML parser reads the response as it streams in. It does not wait for the whole file. Each time it reaches a tag such as <link>, <script> or <img>, it starts a request for the URL in that tag.
Some tags can stop the parser while a file downloads. To avoid wasting that time, browsers run a second, lightweight scan called the preload scanner. It reads ahead in the raw HTML while the main parser is blocked and starts downloads for the URLs it finds.
The preload scanner only sees URLs written in the HTML. It cannot see:
- Images set from JavaScript, for example
img.src = '/photo.jpg'. - Images referenced in CSS with
background-image. - Fonts referenced in CSS with
@font-face. - Anything a script fetches.
These resources are found late, and that delay is the cause of many slow page loads.
CSS blocks rendering
A stylesheet in the <head> is render-blocking. The browser will not paint the page until it has downloaded and parsed that CSS, because painting without it would show unstyled content that then jumps. HTML parsing continues while CSS downloads, so the DOM keeps growing. Only the first paint waits.
CSS also affects scripts. A classic script may read styles, for example through getComputedStyle. So the browser delays running a script until all stylesheets requested before it have finished loading. A slow stylesheet can therefore hold up JavaScript as well.
Two practical results follow:
- Keep critical CSS small and put it in the
<head>. - Do not load large, non-critical stylesheets in a way that blocks the first render. For example, use a
mediaattribute such asmedia="print"for print-only styles. The browser still downloads them, but at lower priority and without blocking rendering.
Scripts: blocking, async and defer
A plain <script src> is parser-blocking. The parser stops, the script downloads and runs, and only then does parsing resume. This is because the script might call document.write or change the DOM that the parser is building.
Two attributes change this behavior:
| Form | Download | Execution | Order kept | Blocks parser |
|---|---|---|---|---|
| `<script src>` | Stops parser | Immediately after download | Yes | Yes |
| `<script async src>` | In parallel | As soon as downloaded | No | Only while running |
| `<script defer src>` | In parallel | After parsing, before `DOMContentLoaded` | Yes | No |
| `<script type="module" src>` | In parallel | Like `defer` by default | Yes | No |
Use defer for scripts that need the DOM or depend on each other. Use async for independent scripts such as analytics, where order does not matter. Inline scripts, which have no src, cannot use async or defer and always run immediately.
Images
Images do not block parsing or the first paint. The browser starts the download and draws the page, and the image appears when it arrives. Images do delay the window load event, which fires only when all of them have finished.
The browser does not know an image's size until the file's header arrives. If your markup gives no size, the text below the image moves down when the image shows up. This movement is called layout shift. Giving the image width and height attributes lets the browser reserve the space in advance.
<img src="/hero.jpg" alt="Mountain at sunrise" width="1200" height="600">
<img src="/gallery-1.jpg" alt="Lake" width="400" height="300" loading="lazy">loading="lazy" tells the browser to postpone the download until the image is near the visible area. Use it for images below the fold. Do not use it on the main image at the top of the page, because it would delay the very image the user came to see.
Fonts
Fonts are the most delayed subresource. The browser requests a font only when three things are true: the CSS contains a matching @font-face rule, the DOM has an element that uses that font family, and that element contains text to draw. The font file is therefore found after the HTML, then the CSS, then the layout work.
@font-face {
font-family: "Body Sans";
src: url("/fonts/body-sans.woff2") format("woff2");
font-display: swap;
}
body {
font-family: "Body Sans", system-ui, sans-serif;
}While the font downloads, the browser must decide what to do with the text. The font-display descriptor controls that choice:
swapshows text immediately in a fallback font and switches when the font arrives.blockhides the text for a short period, then swaps.optionaluses the font only if it arrives very quickly, so there is no later visual change.
Fonts are fetched in a CORS-enabled mode, even from your own origin. This matters when you preload them, as the next section shows.
Hints that change the schedule
You can tell the browser about resources earlier than it would find them.
<head>
<link rel="preconnect" href="https://cdn.example.com">
<link rel="preload" href="/fonts/body-sans.woff2" as="font" type="font/woff2" crossorigin>
<link rel="stylesheet" href="/style.css">
</head>preconnectdoes the DNS lookup, TCP connection and TLS handshake for another origin ahead of time. It saves the setup cost but downloads nothing.preloadstarts downloading a specific file at high priority. Theasattribute tells the browser what kind of file it is, so it can set the right priority and cache entry.- A font preload needs
crossorigin, even for same-origin files. Without it, the preloaded copy is fetched in a different mode and the later real font request cannot reuse it. The font downloads twice.
Browsers also assign priorities on their own. Stylesheets and blocking scripts rank highest, then fonts and defer scripts, then images, with images outside the viewport lowest. The fetchpriority="high" attribute on an <img> raises one image's priority, which helps for the main image at the top of a page.
Connections and caching
Many small requests would be slow if each needed a new connection. With HTTP/1.1, a browser opens up to about six parallel connections per host, and each carries one request at a time. With HTTP/2 and HTTP/3, one connection carries many requests at once (multiplexing), so the number of files matters less than it used to.
Every subresource has its own cache headers. A script with Cache-Control: max-age=31536000, immutable is served from the local cache on later visits with no request at all. Giving versioned file names such as app.3f9c1b.js lets you cache for a long time and still ship changes, because a new version has a new URL.
Observing subresources
In the DevTools Network panel, each row is one request. The Initiator column shows what caused it: the HTML parser, a stylesheet, or a script. The waterfall chart shows when each request started and how long each phase took. A font that starts only after the CSS finishes is the late-discovery pattern from above.
You can also list them from the page itself with the Resource Timing API:
for (const entry of performance.getEntriesByType('resource')) {
console.log(entry.initiatorType, entry.name, Math.round(entry.duration) + ' ms');
}initiatorType has values such as link, script, img, css and fetch. Entries with type css are things like fonts and background images found through a stylesheet.
Common errors
- Putting a large synchronous script in the
<head>. The page stays blank until it downloads and runs. Adddefer. - Preloading a font without
crossorigin. The font is fetched twice. - Lazy-loading the main image. The page's largest visible element loads late.
- Leaving out
widthandheighton images. The layout jumps as images arrive. - Preloading too many files. Preloads compete with each other and with files the page needs more.
Exercise
A page has <link rel="stylesheet" href="/style.css"> in the head. The CSS contains an @font-face rule, and the Network waterfall shows the font request starting only after style.css has finished downloading. Why does the font start so late, and what is one way to start it earlier?
Show answer
The preload scanner reads only the HTML, so it cannot see the font URL inside the CSS. The browser finds the font only after it has parsed the CSS and found text that uses that font family. To start it earlier, add <link rel="preload" href="/fonts/body-sans.woff2" as="font" type="font/woff2" crossorigin> to the HTML head. The crossorigin attribute is required, or the font downloads twice.
Exercise
You have two external scripts. lib.js must run before main.js, and both use the DOM. Which attribute should you put on both, and why would async be wrong?
Show answer
Use defer on both. Deferred scripts download in parallel, run after parsing finishes, and run in document order, so lib.js runs first. async runs each script as soon as it downloads, so main.js could run before lib.js, and it could run before the DOM is complete.