requestIdleCallback and requestAnimationFrame for Non-Blocking JavaScript in WordPress

requestAnimationFrame and requestIdleCallback in WordPress scripts

The browser has one main thread for JavaScript, layout and painting. A loop that inserts 2,000 table rows, or a scroll handler that reads and writes layout on every event, takes that thread away from everything else, and the page stops reacting. Two scheduling functions help: requestAnimationFrame() runs code right before the next paint, requestIdleCallback() runs code when the browser has nothing else to do.

Problem: An admin page of a plugin renders 2,000 inventory rows in one synchronous loop and freezes for almost a second. On the front end, a sticky header reads scrollY and changes styles on every scroll event, and scrolling stutters on phones.

Solution: Render the rows in chunks with requestIdleCallback() and its deadline (with a setTimeout fallback where it is missing), and do the visual update of the header once per frame with requestAnimationFrame(), reading the scroll position in a passive listener.

Render a long list in idle time

// js/inventory-table.js
const idle = window.requestIdleCallback
    ? ( cb ) => window.requestIdleCallback( cb, { timeout: 200 } )
    : ( cb ) => setTimeout( () => cb( { timeRemaining: () => 8, didTimeout: true } ), 16 );

function haRenderInChunks( tbody, items, renderRow, done ) {
    let index = 0;

    function work( deadline ) {
        const fragment = document.createDocumentFragment();
        while ( index < items.length && ( deadline.timeRemaining() > 2 || deadline.didTimeout ) ) {
            fragment.append( renderRow( items[ index ] ) );
            index++;
            if ( deadline.didTimeout && index % 100 === 0 ) break; // do not block when forced
        }
        tbody.append( fragment );

        if ( index < items.length ) {
            idle( work );
        } else if ( done ) {
            done();
        }
    }

    idle( work );
}

function haRow( item ) {
    const tr = document.createElement( 'tr' );
    for ( const value of [ item.sku, item.name, item.stock ] ) {
        const td = document.createElement( 'td' );
        td.textContent = value;
        tr.append( td );
    }
    return tr;
}

async function haInitInventory() {
    const response = await fetch( window.haInventory.endpoint, { headers: { 'X-WP-Nonce': window.haInventory.nonce } } );
    const items = await response.json();
    haRenderInChunks( document.querySelector( '#ha-inventory tbody' ), items, haRow, () => {
        document.querySelector( '#ha-inventory' ).setAttribute( 'aria-busy', 'false' );
    } );
}
haInitInventory();

timeRemaining() tells how many milliseconds of the current idle period are left (at most 50). The loop stops a little before the end so the browser can paint. The timeout option guarantees that the callback runs within 200 ms even when the page is never idle; then didTimeout is true, and the loop renders a fixed chunk of 100 rows instead of everything. The rows are built with textContent, so product names with < or quotes cannot break the markup.

requestIdleCallback() is missing in Safari, which is why the fallback with setTimeout exists. It is not a real idle check, but it splits the work into chunks just as well.

One update per frame with requestAnimationFrame

const header = document.querySelector( '.site-header' );
let lastY = 0;
let ticking = false;

window.addEventListener( 'scroll', () => {
    lastY = window.scrollY;
    if ( ! ticking ) {
        ticking = true;
        requestAnimationFrame( () => {
            header.classList.toggle( 'is-compact', lastY > 80 );
            ticking = false;
        } );
    }
}, { passive: true } );

Scroll events can fire more often than the screen refreshes. The listener only stores the position; the class is toggled at most once per frame, right before the paint. passive: true tells the browser that the listener never calls preventDefault(), so it can scroll without waiting for the script. For a header like this, a CSS-only solution with position: sticky may be enough: position: sticky.

Which one for what

  • requestAnimationFrame(): visual changes that must be in the next frame: animations, positions, classes that change the look. It does not run in background tabs.
  • requestIdleCallback(): work that may wait: rendering rows below the fold, sending analytics, warming a cache, preparing data for the next step.
  • Neither of them: work that must react at once to an input. A click handler should do its visible part immediately and move the rest to one of the two.

For events that fire very often, like input in a search field, debounce is often the better tool: debounce and throttle.

NOTE: Chunked rendering keeps the page responsive, but 2,000 rows in the DOM are still 2,000 rows to lay out. For lists that large, consider pagination or rendering only the visible rows, and move heavy calculations (filtering, sorting) into a Web Worker. The responsiveness that users feel is measured by the Core Web Vitals metric INP: Core Web Vitals in WordPress.