Building a Client-Side Background Remover: Architecture and Lessons

Our background remover is a static HTML page plus one ES module that lazy-imports @imgly/background-removal from a CDN, hands it an image Blob, and gets back a PNG Blob with an alpha channel. There is no backend, no bundler and no build step. This write-up covers the architecture, the loading strategy, and the memory and robustness lessons that took the most iterations to get right, with snippets taken from the production code.

Architecture at a glance

The whole tool lives in tools/bg-remover.js, loaded with <script type="module">. The flow is:

  1. File input change: decode the file, downscale it if its longest side exceeds 4096 px, keep the result as a Blob, and draw it on a canvas as the preview.
  2. Button click: dynamically import the library (first click only), then call removeBackground(blob, config).
  3. Result: decode the returned PNG Blob into an Image, draw it on the same canvas, and show the download button.
  4. Download: canvas.toBlob() as PNG, saved as <name>-no-background.png through a shared helper in utils.js.

The image never goes anywhere except between Blobs, an Image element and a canvas in the same tab.

Why @imgly/background-removal?

IMG.LY's library packages a background-segmentation model together with ONNX Runtime Web and exposes the whole pipeline as one async function: Blob in, Blob out. It fetches its own model and WebAssembly assets, reports progress through a callback, and can emit PNG directly so the alpha channel survives. For a site with no build tooling, a single function with a small config object was the deciding factor. The first run downloads roughly 40 MB of model data, which the browser then caches, and our status message says so up front.

We pin an exact version (1.7.0) in the import URL. A floating version on a CDN means a library update can change behaviour or asset paths under a live page with no deploy on our side.

Loading strategy: dynamic import on first click

A static import at the top of the module would make every visitor pay for the library on page load, including people who only read the page. Instead the import happens inside the click handler, and the resolved function is cached in module scope so later runs skip it:

let removeBackgroundFn = null;

if (!removeBackgroundFn) {
    // Dynamic import keeps the heavy library off the initial page load.
    const module = await import(
        'https://cdn.jsdelivr.net/npm/@imgly/background-removal@1.7.0/+esm'
    );
    removeBackgroundFn = resolveRemoveBackground(module);
    if (typeof removeBackgroundFn !== 'function') {
        throw new Error('Background removal library failed to load (unexpected module shape)');
    }
}

Handling default and named ESM exports

jsDelivr's /+esm endpoint converts npm packages into browser-ready ES modules. Depending on how a package is published and converted, the function you want can arrive as a named export, as the default export, or as a property of a default object. Rather than bet on one shape, we resolve all three:

function resolveRemoveBackground(module) {
    if (typeof module.removeBackground === 'function') return module.removeBackground;
    if (typeof module.default === 'function') return module.default;
    if (module.default && typeof module.default.removeBackground === 'function') {
        return module.default.removeBackground;
    }
    return null;
}

When none match, we log Object.keys(module) as a warning. That one line made an unexpected CDN change a two-minute diagnosis instead of a mystery.

Making a failed import retryable

The background blur tool, which uses the same library to find the subject, taught us a less obvious lesson. Browsers remember a failed module import per specifier, so if the first attempt hits a network blip, retrying the identical URL rejects instantly without touching the network. Adding a fragment makes the specifier unique while fetching the same file:

const specifier = loadAttempt === 0 ? LIB_URL : `${LIB_URL}#retry-${loadAttempt}`;
loadAttempt++;
loadPromise = import(specifier)
    .then((module) => { /* resolve the function as above */ })
    .catch((e) => {
        loadPromise = null; // allow retry on the next click
        throw e;
    });

Memory: capping input at 4096 pixels

Phone cameras produce very large images, and a decoded bitmap costs width × height × 4 bytes before the model allocates anything. A 4096 × 4096 image is already 64 MiB as raw RGBA, and at peak the tab holds the decoded source, the canvas, the model's tensors and the output at the same time. To stay inside what a browser tab can reliably allocate, we downscale anything larger before it reaches the model:

const MAX_DIMENSION = 4096;

const scale = Math.min(1, MAX_DIMENSION / Math.max(width, height));
if (scale === 1) {
    resolve(file);           // small enough: pass the original Blob through
    return;
}
const tmp = document.createElement('canvas');
tmp.width = Math.round(width * scale);
tmp.height = Math.round(height * scale);
tmp.getContext('2d').drawImage(img, 0, 0, tmp.width, tmp.height);
tmp.toBlob((blob) => resolve(blob), 'image/png');

Two details matter. Images under the cap pass through untouched, so most users get a result at exactly their original size. And the downscaled copy is encoded as PNG, not JPEG, so we do not add compression artefacts right before the model looks at the edges.

Threads and cross-origin isolation

ONNX Runtime Web can run multi-threaded WebAssembly, but only with SharedArrayBuffer, which browsers enable only on cross-origin isolated pages (served with Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers). Cross-origin isolation constrains every third-party resource a page loads, and our pages pull several scripts from CDNs, so the site does not set those headers. The runtime then uses its single-threaded WebAssembly path. It is slower on multi-core machines but works the same in every browser, which matters more for a free tool used on phones and old laptops.

Progress reporting users can understand

The library's progress callback receives a key, a current value and a total. Keys for asset downloads start with fetch, which lets us tell people whether they are waiting on the network or on their processor:

const config = {
    output: { format: 'image/png' },   // PNG keeps the alpha channel
    progress: (key, current, total) => {
        if (total) {
            const percent = Math.min(100, Math.round((current / total) * 100));
            const label = key.startsWith('fetch') ? 'Downloading model' : 'Processing';
            setStatus(`${label}: ${percent}%`);
        } else {
            setStatus('Processing image...');
        }
    },
};

Guarding against stale results

Inference takes seconds. If someone picks a second photo while the first is still processing, the slow first result must not paint over the new image. A counter bumped on every upload solves it:

let runToken = 0;

// on file change:
const token = ++runToken;

// on click, after the await:
const blob = await removeBackgroundFn(input, config);
if (token !== runToken) return; // a different image was loaded meanwhile

The same check runs again inside the result image's onload, because decoding the output is a second asynchronous step.

Error handling that never strands the button

Showing transparency without baking it in

The checkerboard behind the result is a CSS background on the canvas element made from four linear-gradient layers. It is never drawn into the pixels, so the exported PNG keeps genuine alpha. On export, the shared downloadImage helper creates an object URL from canvas.toBlob() and revokes it after a one-second timeout, because revoking in the same tick can cancel the download in some browsers.

Lessons worth reusing

The same pattern now powers the background colour changer and the product white-background tool. For a non-technical explanation of what users experience, see how in-browser AI background removal works, and to audit any site's network behaviour, read how to tell if a website uploads your files.

See the implementation in action

Open DevTools on the tool page and watch the module and model load on your first click.

Open the Background Remover