Why optimize JavaScript
Unoptimised JavaScript can block page rendering, increase Time to Interactive (TTI), and negatively impact INP. In modern web, JS bundle sizes often exceed several megabytes, which is especially critical for mobile devices and slow connections.
Main JavaScript optimization techniques
- Minification – remove spaces, comments, rename variables (tools: Terser, UglifyJS).
- Code splitting – break code into chunks loaded on demand (Webpack, Rollup).
- Tree shaking – remove unused code from the bundle (requires modular architecture).
- Defer / async – non‑blocking script loading.
- Compression (gzip / brotli) – reduce data transfer size.
- Caching – Cache-Control headers for repeat visits.
Defer vs Async: what is the difference
html
<!-- Defer: loads in parallel, executes after HTML -->
<script src="app.js" defer></script>
<!-- Async: loads in parallel, executes immediately after loading -->
<script src="analytics.js" async></script>- No attribute – blocks HTML parsing, executes immediately (for critical scripts).
- defer – loads in parallel, executes after HTML is fully loaded (for main JS).
- async – loads in parallel, executes as soon as loaded (for independent scripts like analytics).
Third‑party script optimization
Third‑party scripts (chat widgets, trackers, embedded widgets) are a common cause of performance issues.
- Google Analytics / GTM – use deferred loading via defer or load on user interaction.
- Facebook Pixel – load after user action (e.g., scroll or click).
- Chat widgets – show a static icon and load the script on click.
- Maps (Google Maps) – show a static image placeholder and load JavaScript on click.
Always audit which external scripts are truly necessary. Every third‑party script adds network, parse, and execution overhead, increasing INP and first input delay.
FAQ
What is a long task and why should I avoid it?
A long task is a task that takes longer than 50 ms. It blocks the main thread, making the interface unresponsive. Break long tasks into smaller pieces using setTimeout or requestIdleCallback.
How do I check if my JavaScript is optimized?
Use Lighthouse (Performance tab), the Coverage panel in Chrome DevTools (shows unused code percentage), and the 'Reduce unused JavaScript' report in PageSpeed Insights.
What is code splitting in practice?
You split your bundle into several parts: a main bundle (loaded immediately) and dynamic chunks (loaded when a specific page or component is needed). For example, an e‑commerce cart script loads only when the user clicks 'Checkout'.