Chapter 59: Lazy Loading & Resource Scheduling

Scheduling Non-Critical Work with requestIdleCallback()

**Part 12: Performance & Optimization** — Chapter 59: Lazy Loading & Code Splitting

LEARNING OBJECTIVES
  • Understand the browser frame budget (16.67ms at 60Hz) and idle time slices.
  • Schedule non-critical work (analytics tracking, pre-caching, client log flushes) during idle periods using requestIdleCallback().
  • Use deadline.timeRemaining() to break large tasks into chunks without freezing the UI.
  • Provide polyfills for Safari via setTimeout and scheduler.postTask().
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

💻 Interactive Code Playground


// Process heavy queue without blocking 60fps animations or user input
function processQueue(items, processItem) {
  let index = 0;

  function doWork(deadline) {
    // Run work as long as the browser has >2ms of idle time in this frame
    while (deadline.timeRemaining() > 2 && index < items.length) {
      processItem(items[index]);
      index++;
    }

    // If items remain, schedule another idle callback
    if (index < items.length) {
      requestIdleCallback(doWork, { timeout: 2000 });
    }
  }

  if ('requestIdleCallback' in window) {
    requestIdleCallback(doWork, { timeout: 2000 });
  } else {
    // Safari fallback
    setTimeout(() => {
      items.forEach(processItem);
    }, 50);
  }
}

📌 Key Takeaways

  • requestIdleCallback yields the main thread to user interactions, animations, and layout recalculations.
  • Always provide a { timeout: 2000 } option to ensure work eventually executes even under heavy CPU loads.
  • --

❓ Knowledge Check

1. Which of the following is correct?

2. Which of the following is correct?