The Cost of JavaScript: Bundle Size, Parsing and Hydration
Why JavaScript costs more than its bytes: parse and execution time per device, async vs defer, tree shaking, code splitting, polyfills and third parties.
JavaScript cost: common questions
What is the difference between async and defer?
Both download without blocking parsing. async runs the script as soon as it arrives, in any order. defer waits until the HTML is parsed and runs scripts in document order.
Related chapters
- Core Web Vitals in Production: LCP, INP and CLS
- Critical Rendering Path Explained: DOM, CSSOM, Paint
- Critical CSS: Inline Above-the-Fold Styles
- CSS Performance: Selectors, @import and Layout Cost
- HTTP Caching Explained: Cache-Control, ETag, CDN
- Lazy Loading Images and Code: Best Practices
- List Virtualization (Windowing) in React Explained
- Intersection Observer API Explained, with Examples
- How Mobile Browsers Work: Camera, Permissions, Quirks
- Frontend Performance Case Studies: Netflix, Airbnb, Flipkart
Keep learning
Overview
Chapter 9 · javascript and bundle cost JavaScript costs twice: once on the wire, again on the CPU
7. What you decide in production
Measure before you cut Coverage tab finds unused bytes, the bundle analyzer finds who owns them, the Performance panel shows when they run. Coverage: 62% unused analyzer: who? Performance: when? DevTools Coverage shows bytes that never ran on this page. A bundle analyzer (rollup-plugin-visualizer, webpack-bundle-analyzer, source-map-explorer) shows which dependency owns them. The Performance panel shows the long tasks they cause. Budgets fail the build Initial JavaScript compared with a budget line. new dep Put a size limit on each entry chunk in CI (size-limit, bundlesize, Lighthouse CI). A pull request that adds 60 KB has to say why. Budgets drift upward one “small” dependency at a time. Split long tasks One 300 millisecond task blocks input. The same work split into chunks lets a click run in between. one task 300ms: click waits Anything over 50 ms is a long task and delays the next interaction (INP). Break loops into chunks and yield between them: scheduler.yield() where available, otherwise setTimeout(0) or requestIdleCallback for low-priority work. Hydration is JavaScript too Full hydration runs JavaScript for the whole page. Islands hydrate only the interactive parts. full page hydrate everything Server-rendered HTML looks ready before it is. Hydration re-runs components to attach handlers, and the page ignores taps until it finishes. Islands, partial hydration and React Server Components ship JavaScript only for the parts that are interactive. ES modules replaced loaders Script loaders then and now RequireJS / Alameda (AMD) to order async scripts type="module" + import, deferred and ordered Animation without a library Prefer CSS transitions, then the Web Animations API, then requestAnimationFrame, and a library last. CSS transition rAF loop +13 KB library CSS transitions and element.animate() ship with the browser and can run on the compositor. A timer loop should be a requestAnimationFrame loop. Reach for an animation library only when animation is the product. Compress and cache well A 300 kilobyte script is about 90 kilobytes with gzip and about 75 with Brotli. Serve Brotli for text, minify, and give hashed chunks a year of immutable caching. Compression shrinks the download only: the CPU still parses the full uncompressed size. Every dependency is a decision Questions before adding a dependency Does the platform already do this? Does it tree-shake? What does it cost gzipped? Check the platform first, then the cost (bundlephobia, pkg-size), then whether it is ESM with sideEffects: false. Start with the smallest thing that works and upgrade when it stops working, not before. Fast laptop, cable Mid phone, 4G Low-end phone, 3G
1. Same bytes, very different bills
Compare a JavaScript bundle with an image of the same compressed size. Both download. Only the script then occupies the main thread. parse + compile parse + compile (main thread) execute (main thread) image decode (off main thread) the CPU actually parses main thread busy long tasks' worth (50 ms each) Scripts ran in order. app.js ran before lib.js. Modern browser: no polyfill request. The form submit uses native fetch. Old browser: the polyfill loads right after the page, long before the user can submit the form. earliest submit html + app reads, fills form Zero extra bytes. Most of your visitors are here. The polyfill arrives in the background, long before the first fetch() call. Nobody waits.
6. Third-party scripts: you own their cost
An A/B test, a chat widget and a tag manager. Each loads someone else’s JavaScript on your main thread. Choose how each one loads. A/B test Sync in head + hide page Decide on server / edge Chat widget (250 KB) Load with the page Facade, load on click Tag manager Sync in head async, after load first paint your page A/B: page hidden main thread chat widget Client-side A/B tools often hide the page until the variant loads (anti-flicker), which turns their latency into yours. Deciding the variant on the server or at the edge removes the hidden-page wait. The chat widget parses 250 KB that most visitors never use. A synchronous tag manager blocks the parser, and every tag inside it inherits that priority. Loaded after the page, the same tags compete with nothing the reader is waiting for.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.