Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Web Performance & Core Web Vitals
  1. 1.Introduction to Web Performance & Business Impact
  2. 2.Core Web Vitals & Practical Measurement Tools
  3. 3.Optimizing the Critical Rendering Path & Basic Asset Delivery
  4. 4.JavaScript Performance & Bundle Optimization
  5. 5.Image, Video, and Media Optimization Strategies
  6. 6.Network Performance: HTTP/2, Caching, and CDNs
  7. 7.Resource Hints & Advanced Loading Strategies
  8. 8.Frontend Architectures & Server-Side Rendering Performance
  9. 9.Performance Budgets, RUM, and Continuous Monitoring
  10. 10.Advanced Browser APIs & Offloading Work with Workers
Web Performance & Core Web Vitals
10

Web Fundamentals · Lesson 10 of 10 · 4 min

Advanced Browser APIs & Offloading Work with Workers

This is about proving you know how to keep the main thread free, even when the work is unavoidable.

Stop blocking the main thread with Observers

For years, the answer to "run code when the user scrolls" was an onscroll listener. The answer to "react to a container changing size" was onresize or a setInterval loop. These are expensive, fire too often, and force layouts. They are an anti-pattern.

The modern answer is to use Observers. They let the browser handle the detection efficiently and call your code only when something actually happens.

  • IntersectionObserver: Use this for lazy-loading images or components, triggering animations, or implementing infinite scroll. It tells you when an element enters or leaves the viewport. This is vastly superior to tracking element positions inside a scroll handler.
  • ResizeObserver: Use this for "element queries"—making a component respond to its own size, not just the viewport's. It's the right tool for a chart that needs to re-render when its parent div is resized by a user.

The interview question: "How would you implement lazy-loading for images?" Your answer should start with IntersectionObserver. Mentioning data-src attributes is a good follow-up. Contrasting it with the performance nightmare of a scroll listener that calls getBoundingClientRect() shows you know the history and the "why."

The trap: The observer callback itself still runs on the main thread. If you do heavy, synchronous work inside the callback, you are still blocking the UI. Keep callbacks fast. If the work is complex, the observer's job is just to trigger that work, which you might then offload.

When to actually use a Web Worker

A Web Worker is a script running on a separate thread. This is your escape hatch for heavy CPU-bound work that would otherwise freeze the page for hundreds of milliseconds. Think client-side data processing, complex calculations, or image manipulation.

Do not use a worker for I/O-bound tasks like a standard fetch call. The fetch API is already asynchronous and non-blocking. A worker adds unnecessary complexity for that.

The main thread needs to be free to render frames, ideally every 16ms for a 60fps experience. If you have a JavaScript task that takes 200ms of pure computation (like sorting a massive array or applying a complex filter), the UI will be frozen for that entire duration. Moving that 200ms task to a worker means the main thread is free. The user can still scroll and click.

This is the code you'll write. The main script creates the worker and listens for messages. The worker script listens for a message, does the work, and posts the result back.

// main.ts (main thread script)
const fibWorker = new Worker('fibonacci.js');

// Listen for results from the worker
fibWorker.onmessage = (event) => {
    console.log('Result from worker:', event.data);
    // Update the UI here
};

// Handle errors
fibWorker.onerror = (error) => {
    console.error('Worker error:', error.message);
};

// Send a task to the worker
document.getElementById('calculateBtn').addEventListener('click', () => {
    const num = 40;
    console.log('Asking worker to calculate fibonacci for', num);
    fibWorker.postMessage(num);
});

// fibonacci.js (worker script)
function calculateFibonacci(n) {
    if (n <= 1) return n;
    return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);
}

// Listen for tasks from the main thread
onmessage = (event) => {
    const result = calculateFibonacci(event.data);
    // Send the result back
    postMessage(result);
};

How to talk about Worker communication

Workers cannot touch the DOM. Communication happens exclusively through postMessage.

When you call postMessage(data), the data is not shared; it's copied using the structured clone algorithm. For small JSON objects, this is fine. For a 50MB ArrayBuffer, this copy operation is slow and memory-intensive, defeating the purpose of the worker.

This is a critical detail in an interview.

The senior-level answer: "For large data, you must use Transferable Objects. When you transfer an ArrayBuffer from the main thread to a worker, its ownership is moved, not copied. The operation is near-instantaneous. The main thread can no longer access that buffer, which prevents race conditions."

The syntax is worker.postMessage(largeBuffer, [largeBuffer]). The second argument is a list of objects to transfer.

This flow shows the clear boundary between the threads.

Syncing tabs: BroadcastChannel and SharedWorkers

Sometimes you need to coordinate state across different tabs of the same origin.

BroadcastChannel is the simple solution. It's a pub/sub mechanism. A tab can post a message to a named channel, and all other tabs listening to that channel will receive it. It's perfect for "user logged out in another tab, so log out here too." It's fire-and-forget.

SharedWorker is more powerful and complex. It's a single worker script that can be accessed by multiple browser contexts (tabs, iframes) from the same origin. Unlike a BroadcastChannel, the SharedWorker has its own state. It can act as a central state manager, a WebSocket connection manager, or a shared cache, preventing each tab from duplicating resources.

Choose BroadcastChannel for simple notifications. Choose SharedWorker when you need a single, stateful agent coordinating multiple clients.

Try it

Take a function in one of your projects that does heavy data manipulation (e.g., filtering a large list based on multiple criteria, preparing data for a chart). Move it into a dedicated Web Worker. Measure the main thread blocking time before and after using the Performance tab in DevTools.

Next: This course is complete. Prepare for your interviews by practicing with our mock interview tool.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Performance Budgets, RUM, and Continuous Monitoring