- Courses
- đ»Programming Languages
- đJavaScript
- Tooling and Performance
- Performance Optimization
On this page
Performance Optimization: Execution and Rendering
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
In professional web development, performance is a core requirement of the architecture. A high-performance application must manage two critical areas: the frequency of JavaScript execution and the efficiency of the browser's rendering engine. By mastering Debouncing, Throttling, and the reduction of Reflows, you ensure that your application remains responsive even under heavy computational or event-driven load.
Managing Event Frequencyâ
High-frequency eventsâsuch as scroll, resize, mousemove, or keypressâcan fire dozens or even hundreds of times per second. If these events trigger expensive operations like API calls or DOM manipulation, they will saturate the main thread and cause "jank" (stuttering).
Debouncingâ
Debouncing ensures that a function is only executed after a specific period of inactivity. Every time the event is triggered, the "wait" timer resets. This is ideal for scenarios where you only care about the final state of an action.
- Use Case: A search bar with autocomplete. You don't want to hit the API on every keystroke; you wait until the user has stopped typing for 300ms.
function debounce(func, delay) {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}
Throttlingâ
Throttling ensures that a function is executed at most once every $X$ milliseconds. Unlike debouncing, it guarantees regular execution during a continuous event. This is ideal for scenarios where you need to track progress over time.
- Use Case: Infinite scrolling. You want to check how far the user has scrolled every 200ms to determine if you should load more content, rather than waiting for them to stop scrolling entirely.
function throttle(func, limit) {
let inThrottle;
return (...args) => {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
Minimizing Reflows and Repaintsâ
To render a page, the browser goes through a pipeline: JavaScript -> Style -> Layout -> Paint -> Composite. To achieve a smooth 60 frames per second (fps), the browser has approximately 16.6ms to complete this entire cycle.
Reflow (Layout)â
A Reflow occurs when the browser must re-calculate the position and geometry of elements in the document. This is the most "expensive" part of the rendering pipeline because changing one element can cause a chain reaction across its parents and siblings.
Triggers for Reflow:
- Changing box model properties:
width,height,padding,margin,border. - Changing typography:
font-size,line-height,text-align. - Manipulating the DOM:
appendChild(),removeChild(). - Querying layout properties:
offsetHeight,getComputedStyle(),getBoundingClientRect().
Repaintâ
A Repaint occurs when changes are made to an element's appearance that do not affect its layout (e.g., color, background-color, visibility). While cheaper than a reflow, frequent repaints still consume CPU and GPU resources.
Eliminating Layout Thrashingâ
Layout Thrashing occurs when you perform a series of "read/write" operations on the DOM in quick succession. Reading a layout property (like offsetWidth) forces the browser to perform a reflow to provide the accurate value. If you then write to the DOM immediately after, the browser's previous layout calculation is invalidated.
The "Read-First, Write-Last" Patternâ
To prevent thrashing, always batch your "reads" (getting data from the DOM) and then batch your "writes" (updating the DOM).
// BAD: Causes layout thrashing
for (let i = 0; i < paragraphs.length; i++) {
const width = div.offsetWidth; // Read (Forced Reflow)
paragraphs[i].style.width = width + "px"; // Write
}
// GOOD: Batched operations
const width = div.offsetWidth; // Single Read
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.width = width + "px"; // Batched Writes
}
Expert Optimization Strategiesâ
- Use
requestAnimationFrame(rAF): For visual updates and animations, userAFinstead ofsetTimeout. This tells the browser to execute the code right before the next repaint, aligning your changes perfectly with the screen refresh rate. - Off-screen DOM Manipulation: When building large structures, create them in a
DocumentFragmentor keep the parent elementdisplay: nonewhile modifying it. This prevents the browser from reflowing the page for every single child added. - CSS over JavaScript: Favor CSS transitions and animations over JavaScript-driven ones. CSS animations often run on a separate "Compositor Thread," which keeps the UI smooth even if the main JavaScript thread is busy.
- Hardware Acceleration: Use properties like
transformandopacityfor animations. These trigger neither reflow nor repaintâthey only trigger "Compositing," which is handled directly by the GPU.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Scalable Architecture
Next
Web APIs
-
Managing Event Frequency
- Debouncing
- Throttling
-
Minimizing Reflows and Repaints
- Reflow (Layout)
- Repaint
-
Eliminating Layout Thrashing
- The "Read-First, Write-Last" Pattern
-
Expert Optimization Strategies
