JavaScript Loading and Runtime Performance
Ship less JavaScript with code splitting and tree shaking, load scripts smartly and keep the main thread free of long tasks.
Advanced · about 5 hours · difficulty 4/5
Learn first: Core Web Vitals and Performance Metrics, Build Tools and Bundlers, Suspense, Error Boundaries and Concurrent Features
JavaScript is the most expensive resource per byte: it must be downloaded, parsed, compiled and executed on the main thread, where it competes with user input. Most slow modern sites are slow because of JavaScript.
Ship less
- Analyse the bundle (
rollup-plugin-visualizer,vite-bundle-visualizer, source-map-explorer) and question every large dependency. Swap heavy libraries for lighter ones or native APIs (Intlinstead of moment, nativefetchinstead of a big HTTP client). - Code splitting: split by route and lazy-load heavy, rarely used features (rich text editors, charts, maps) with dynamic
import(). - Tree shaking works best with ES modules and named imports.
- Audit third-party scripts (analytics, chat widgets, tag managers); they are frequent culprits.
Load it well
<script type="module">anddeferdo not block parsing; avoid synchronous scripts in the head.- Preload critical resources and prefetch likely next routes.
- Serve modern syntax to modern browsers rather than transpiling everything down.
Keep the main thread free
- A long task is anything over 50 ms; it delays response to input and hurts INP.
- Break up work: yield with
scheduler.yield()orsetTimeout, process in chunks, or move heavy computation to a Web Worker. - Debounce and throttle expensive handlers (scroll, resize, input).
- Virtualise long lists and avoid layout thrashing (reading layout then writing styles in a loop).
- In React, see the rendering topic: move state down and memoise genuinely expensive work.
Good enough to move on
You can find the biggest dependencies in a bundle, lazy-load a heavy route, identify long tasks in the Performance panel and break one up.
Key concepts
- Cost of JavaScript
- Bundle analysis
- Route and component code splitting
- Dynamic import()
- defer, async and module scripts
- Preload and prefetch
- Long tasks and yielding
- Third-party script management
- Debounce and throttle
Mini project
Take a React app, cut its initial JavaScript by at least 30%: analyse the bundle, replace one heavy dependency, lazy-load two routes and a heavy widget, and document before and after sizes and INP.
Check yourself
Why does a 300 KB JavaScript file hurt more than a 300 KB JPEG on a mid-range phone?
Free resources
- Reduce JavaScript payloads with code splitting (web.dev)
- Optimize long tasks (web.dev)
- Optimize Interaction to Next Paint (web.dev)