HTML Performance Optimization
Speed is a feature users feel before they read a single word of your copy. A page that stalls on its first paint loses conversions, rankings and trust, and almost every stall traces back to decisions made in the HTML head: which scripts block parsing, which fonts load late, which images decode during scroll. This lesson walks through the browser's loading pipeline, then maps each performance lever — script strategies, resource hints, lazy loading and measurement — to the exact markup that controls it.
How the browser actually spends its first seconds
When the browser receives HTML it starts a parser that walks the document from top to bottom, building the DOM as it goes. A classic script tag without attributes halts that parser: the browser must fetch the file, execute it, and only then resume, which is why a slow analytics snippet in the head can blank the entire page. CSS blocks script execution but not DOM construction, while images and fonts compete for bandwidth after the initial markup arrives.
The performance budget is expressed through three user-facing metrics. Largest Contentful Paint (LCP) captures when the biggest visible element — usually a hero image or headline block — renders; aim for under 2.5 seconds. Interaction to Next Input (INP) reflects how quickly the page responds to the first tap or click; keep it under 200 milliseconds. Cumulative Layout Shift (CLS) measures unexpected movement as late-loading content pushes things around; stay under 0.1. Notice that markup decisions dominate all three: a preloaded hero fixes LCP, a deferred script protects INP, and explicit width and height attributes on images protect CLS.
Script loading strategies: async, defer and modules
Three attributes change how scripts interact with parsing, and choosing the wrong one is the most common performance bug in static HTML. An async script downloads in parallel and executes the moment it arrives, pausing the parser — correct for independent third-party code such as analytics, harmful for anything that touches the DOM structure. A defer script also downloads in parallel but executes only after the document has finished parsing, preserving order relative to other deferred scripts — the right default for application code. Module scripts are deferred by default and can import other modules, which removes another class of ordering bugs.
<head>
<meta charset="utf-8">
<title>Shop — Fast by default</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preload" as="style"
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap">
<link rel="preload" as="font" type="font/woff2" crossorigin
href="/fonts/inter-var.woff2">
<link rel="preload" as="image" href="/img/hero-1600.webp"
imagesrcset="/img/hero-800.webp 800w, /img/hero-1600.webp 1600w"
imagesizes="100vw">
<link rel="stylesheet" href="/css/critical.css">
<link rel="stylesheet" href="/css/rest.css" media="print" onload="this.media='all'">
<script src="https://analytics.example.com/tracker.js" async></script>
<script src="/js/app.js" defer></script>
<script type="module" src="/js/cart-widget.js"></script>
</head>
The inline media="print" swap on the non-critical stylesheet is a classic trick: the browser fetches it at low priority without blocking first paint, then promotes it to all once the document is interactive. Modern builds often achieve the same result by splitting CSS at build time, but the markup pattern remains useful for legacy stylesheets.
Resource hints: preload, prefetch and preconnect
Resource hints tell the browser what will be needed soon, without forcing an immediate full load. Preload fetches a critical asset at high priority for the current navigation — hero images, the fonts used in the first viewport, the main stylesheet. Prefetch grabs something needed for a likely next navigation (the pricing page's JavaScript bundle) at the lowest priority, so it rarely competes with current-page work. Preconnect performs DNS lookup, TCP handshake and TLS negotiation ahead of time against a known origin, shaving 100–300 milliseconds off the first request to an API or font host. dns-prefetch is the lighter fallback for older browsers.
Use hints sparingly. A page that preloads six fonts and three scripts spends its priority budget on speculation and degrades the assets that genuinely block rendering. Measure before and after with the Network panel: a correct preload moves an asset from "discovered late" to "started at request start," and LCP should drop accordingly.
| Hint | When it runs | Priority | Best use |
|---|---|---|---|
| preload | Immediately, current page | High | Hero images, critical fonts, main CSS |
| prefetch | Idle time, next navigation | Lowest | Likely next-page bundles |
| preconnect | Idle, current origin pool | High | Font hosts, API origins |
| dns-prefetch | Idle, DNS only | Low | Older browser support for third parties |
| prerender | Idle, full next page | Lowest | Confident single next step, used rarely |
Lazy loading images, iframes and everything else
The native loading="lazy" attribute covers images and iframes with zero JavaScript: the browser defers fetching until the element approaches the viewport, then loads it just in time. Combine it with explicit width and height attributes (or CSS aspect-ratio) so the browser can reserve space and CLS stays low. Keep your Largest Contentful Paint candidate eager — lazily loading the hero image trades a headline metric for a few bytes you did not need to save.
For content that is not an image or iframe — embeds, background sections, entire route fragments — an IntersectionObserver gives the same pattern with more control:
<section class="recipe-grid" aria-live="polite">
<article class="recipe-card">
<img src="/img/pasta-thumb.jpg" width="480" height="320"
alt="Bowl of cacio e pepe" loading="lazy" decoding="async">
<h3>Cacio e pepe</h3>
</article>
</section>
<div class="map-embed" data-src="/embed/delivery-map.html"
role="region" aria-label="Delivery map">Loading map…</div>
<script>
const lazyRegions = document.querySelectorAll('.lazy-embed');
if ('IntersectionObserver' in window) {
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const region = entry.target;
region.src = region.dataset.src;
region.classList.add('is-loaded');
observer.unobserve(region);
}
}, { rootMargin: '200px 0px' });
lazyRegions.forEach((region) => observer.observe(region));
} else {
lazyRegions.forEach((region) => { region.src = region.dataset.src; });
}
</script>
The rootMargin of 200 pixels starts the fetch slightly before the region scrolls into view, hiding network latency from the user. The feature-detection fallback keeps older browsers working, which is the graceful-degradation half of the pattern.
Measuring instead of guessing
Markup tweaks without measurement produce cargo cult optimization. The Performance panel in browser dev tools records a full trace: look at the timing track for when the first paint, first contentful paint and largest contentful paint occur, then check which requests were in flight during those windows. The Network panel's priority column reveals whether your preloads actually started early. For field data, the Navigation Timing and Resource Timing APIs expose the same numbers from real sessions:
<script>
window.addEventListener('load', () => {
const nav = performance.getEntriesByType('navigation')[0];
console.log('DOM interactive:', Math.round(nav.domInteractive), 'ms');
console.log('DOMContentLoaded:', Math.round(nav.domContentLoadedEventEnd), 'ms');
console.log('Load event:', Math.round(nav.loadEventEnd), 'ms');
const lcp = [];
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) lcp.push(entry);
}).observe({ type: 'largest-contentful-paint', buffered: true });
window.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden' && lcp.length) {
console.log('LCP candidate:', Math.round(lcp[lcp.length - 1].startTime), 'ms');
}
});
const slowResources = performance.getEntriesByType('resource')
.filter((r) => r.duration > 300)
.sort((a, b) => b.duration - a.duration)
.slice(0, 10);
slowResources.forEach((r) => {
console.log(Math.round(r.duration) + 'ms', r.name);
});
});
</script>
Reporting only the slowest handful of resources keeps the console useful; the goal is to find the one stylesheet or font that drags everything else down.
A practical optimization checklist
Before calling a page fast, walk this sequence against real markup. Confirm that no render-blocking script sits in the head without async or defer. Confirm the LCP image is preloaded and eager, and that every below-the-fold image is lazy with dimensions set. Confirm fonts use font-display: swap and are preloaded only if they appear in the first viewport. Confirm third-party origins are preconnected once and loaded once. Confirm above-the-fold CSS is inlined or shipped as a small critical file, with the remainder deferred. Then re-run the trace on a mid-range mobile device profile, because desktop numbers hide the CPU bound stalls where most real users live.
Performance work compounds: each saved hundred milliseconds improves every subsequent interaction, and the markup-level fixes described here cost nothing at runtime compared with framework-level rewrites. Start in the head, measure in the field, and keep the budget visible to the whole team.
Common Mistakes
Putting an application script in the head without defer, blocking the parser while it downloads
Fix: Use defer for ordered application code, async for independent third parties, and type module for ES modules that should be deferred automatically.
Lazily loading the hero image that defines Largest Contentful Paint
Fix: Keep the LCP candidate eager and preloaded; apply loading lazy only to content well below the fold.
Preloading every font weight and icon sprite on every page
Fix: Audit the Network panel, preload only assets visible in the first viewport, and let the rest load at normal priority.
Forgetting width and height on images, so lazy content shifts the layout when it arrives
Fix: Always set intrinsic dimensions or CSS aspect-ratio so the browser can reserve space before the bytes land.
Optimizing from lab scores alone on a fast desktop connection
Fix: Profile with a mid-range mobile CPU throttled profile and confirm changes with field data from real sessions.
Shipping the full stylesheet unconditionally because it is simpler
Fix: Split critical above-the-fold CSS inline, load the rest with a print-media swap or as a non-blocking stylesheet.
Key Takeaways
- Parser-blocking scripts are the classic speed killer; defer is the default for application code and async is for independent third parties.
- Preload what the first viewport needs, preconnect to known third-party origins, and prefetch only confident next-navigation assets.
- Native loading lazy covers images and iframes; use IntersectionObserver for embeds and fragments, and always reserve space to protect CLS.
- Protect the three Core Web Vitals: LCP under 2.5s, INP under 200ms, CLS under 0.1 — markup decisions drive all of them.
- Resource Timing and PerformanceObserver give you the numbers; optimize only what measurement proves is slow.
- Small, verified markup fixes outperform speculative rewrites: fewer blocking requests, earlier critical assets, reserved layout space.