The Cost of Performance
In web development, performance is not just a feature; it is a fundamental aspect of user experience. Studies consistently show that even millisecond delays in page loading correlate with significantly higher bounce rates and lower user engagement. Mastering web performance requires understanding how the browser processes resources and identifying bottlenecks.
The Critical Rendering Path (CRP)
The CRP is the sequence of steps the browser takes to convert HTML, CSS, and JavaScript into pixels on the screen.
- DOM: Parse HTML and build the Document Object Model.
- CSSOM: Parse CSS and build the CSS Object Model.
- Render Tree: Combine DOM and CSSOM to determine which elements are visible.
- Layout: Calculate the geometry (position and size) of each element.
- Paint: Fill in the pixels for each element.
JavaScript’s Role: JavaScript is a parser-blocking resource. When the browser encounters a <script> tag, it must stop building the DOM, download the script, and execute it before continuing.
Optimization Techniques
1. Script Attributes: Async and Defer
To prevent parser blocking:
async: Download the script in the background and execute it the moment it’s ready (may interrupt the parser).defer: Download in the background and only execute after the DOM is fully parsed. Usedeferfor most scripts.
2. Code Splitting and Lazy Loading
Instead of sending a single 2MB JavaScript bundle, use Dynamic Imports to split your code into smaller chunks. Load only the code required for the current route or action.
3. Tree Shaking
Modern bundlers use static analysis to identify “dead code”—functions or modules that are imported but never used—and remove them from the final bundle.
Core Web Vitals (CWV)
Google introduced Core Web Vitals as a standardized set of metrics to measure user experience:
- Largest Contentful Paint (LCP): How long it takes to render the largest visible element (loading performance).
- First Input Delay (FID): Time from user interaction to the browser’s response (responsiveness).
- Cumulative Layout Shift (CLS): Measures visual stability (do elements jump around while loading?).
Memory Management and Garbage Collection
JavaScript uses a Mark-and-Sweep garbage collection algorithm. The engine starts from “roots” (like the global object) and marks all reachable objects. Anything not marked is considered unreachable and is cleared.
Common Memory Leaks:
- Uncleared Timers:
setIntervalcontinuing to run after a component unmounts. - Forgotten Event Listeners: Listeners attached to
windowordocumentthat are never removed. - Closures: Over-retaining large objects in a long-lived closure scope.
Which script attribute is generally preferred for modern web applications to ensure scripts don't block DOM parsing?
Image Optimization
Images often account for the majority of a page’s weight. Use modern formats like WebP or AVIF, implement responsive images with srcset, and use Lazy Loading for below-the-fold content.