Offload Heavy Computation to Web Workers in WordPress JavaScript

Web Workers for heavy JavaScript in the WordPress admin

JavaScript in the page runs on the main thread, the same thread that paints the screen and reacts to clicks. Filtering and sorting 50,000 rows there freezes the page for a second on every keystroke. A Web Worker runs a script in a separate thread: the page sends it data, the worker computes, and the page stays responsive while it waits for the answer.

Problem: An admin page of a plugin shows a product list of 50,000 rows with a live search, and every typed letter blocks the page for 800 ms.

Solution: Load the data once, send it to a worker with postMessage(), let the worker filter and sort and return only the visible slice, ignore answers to outdated requests, and pass the worker’s URL from PHP with wp_localize_script() or an inline script.

The worker

// js/table-worker.js
let rows = [];

self.onmessage = ( event ) => {
    const { type, payload, id } = event.data;

    if ( type === 'load' ) {
        rows = payload.map( ( row ) => ( { ...row, search: `${ row.sku } ${ row.name }`.toLowerCase() } ) );
        self.postMessage( { id, type: 'loaded', total: rows.length } );
        return;
    }

    if ( type === 'query' ) {
        const term = payload.term.toLowerCase().trim();
        const dir = payload.dir === 'desc' ? -1 : 1;
        const key = payload.sort;
        const found = term ? rows.filter( ( row ) => row.search.includes( term ) ) : rows.slice();
        found.sort( ( a, b ) => ( a[ key ] > b[ key ] ? dir : a[ key ] < b[ key ] ? -dir : 0 ) );
        self.postMessage( { id, type: 'result', total: found.length, rows: found.slice( 0, 100 ) } );
    }
};

The data is sent to the worker once and kept there. Each query returns only the first 100 rows; copying 50,000 rows back to the page on every keystroke would cost more than the filtering. The search string per row is prepared once on load.

The page

// js/table.js
const worker = new Worker( window.haTable.workerUrl );
let lastId = 0;

worker.onmessage = ( event ) => {
    const { id, type, rows, total } = event.data;
    if ( type === 'result' && id === lastId ) {
        renderRows( rows, total );
    }
};

async function init() {
    const response = await fetch( window.haTable.dataUrl, { headers: { 'X-WP-Nonce': window.haTable.nonce } } );
    worker.postMessage( { type: 'load', payload: await response.json(), id: 0 } );
}

document.querySelector( '#ha-search' ).addEventListener( 'input', ( event ) => {
    lastId++;
    worker.postMessage( { type: 'query', id: lastId, payload: { term: event.target.value, sort: 'name', dir: 'asc' } } );
} );

function renderRows( rows, total ) {
    const tbody = document.querySelector( '#ha-table tbody' );
    tbody.replaceChildren( ...rows.map( ( row ) => {
        const tr = document.createElement( 'tr' );
        [ row.sku, row.name, row.stock ].forEach( ( value ) => {
            const td = document.createElement( 'td' );
            td.textContent = value;
            tr.append( td );
        } );
        return tr;
    } ) );
    document.querySelector( '#ha-count' ).textContent = `${ total } products`;
}

init();

The request ID makes sure only the answer to the latest keystroke is rendered; slower answers to older queries are dropped. Cells are filled with textContent, so product names cannot inject HTML.

Pass the URLs from PHP

add_action( 'admin_enqueue_scripts', function ( $hook ) {
    if ( 'toplevel_page_ha-products' !== $hook ) {
        return;
    }
    wp_enqueue_script( 'ha-table', plugins_url( 'js/table.js', __FILE__ ), [], '1.0.0', true );
    wp_localize_script( 'ha-table', 'haTable', [
        'workerUrl' => plugins_url( 'js/table-worker.js', __FILE__ ),
        'dataUrl'   => rest_url( 'ha/v1/products' ),
        'nonce'     => wp_create_nonce( 'wp_rest' ),
    ] );
} );

A worker must be loaded from the same origin as the page, which is the case for files in the plugin folder. It has no access to the DOM, window or jQuery; it only exchanges messages. The REST endpoint behind dataUrl needs its own permission_callback with a capability check.

NOTE: Before reaching for a worker, try the cheaper fixes: debounce the input (see debounce and throttle), render only the visible rows, or filter on the server with a paginated query. A worker is the right tool when the computation itself is heavy and must happen in the browser.