MonkeyLoader All articles
Accessibility

Check the Photo After They Pick It: Keeping Image Validation Off the Critical Path

MonkeyLoader
Check the Photo After They Pick It: Keeping Image Validation Off the Critical Path

Photo: Robert Rexach www.mkt3000.com, Public domain, via Wikimedia Commons

A photo lab for people who haven't taken a photo yet

There's a genre of UK form that collects a passport-style photograph: concessionary travel passes, resident permits, season tickets, bus pass renewals at the council. The specs are fussy — size, head proportions, plain background, file under a certain number of megabytes — and somebody decided years ago that the kindest thing to do was check the image in the browser before upload.

Fine idea. The implementation usually isn't. A face-detection library, a canvas pipeline and a JPEG parser get bundled into the main entry point, and every visitor pays for it: the person who came to read the eligibility rules, the person who hasn't got a photo yet, the person on a library computer in Hartlepool working through it slowly with a paper notes sheet beside them.

On one such form, LCP went from 1.2 seconds to 3.4 seconds after the checker landed. For a job that only happens after someone picks a file.

What actually has to happen before the first upload

Nothing at all. The browser can tell you the file's name, MIME type and byte size the instant it's selected. Every other check — dimensions, background, head size, whether the thing is even a face — is optional, and all of it can happen after the file exists.

So move it there.

const input = document.querySelector('#photo');
const status = document.querySelector('#photo-status');
let pendingFile = null;

input.addEventListener('change', async () => {
  const file = input.files && input.files[0];
  if (!file) return;
  pendingFile = file;
  status.textContent = 'Checking your photo…';

  try {
    const { checkPhoto } = await import('/js/photo-check.js');
    const result = await checkPhoto(file);
    status.textContent = result.ok
      ? 'Your photo looks fine.'
      : result.message;
    document.body.dataset.photoValid = String(result.ok);
  } catch {
    // The checker failed to load or threw. That is never the visitor's problem.
    status.textContent = 'We could not check your photo. You can still continue.';
    document.body.dataset.photoValid = 'unknown';
  }
});

import() gives you a separate chunk that the browser fetches once and caches. If you want to be a bit kinder, warm it on focus of the file input — that's a genuine signal that someone is about to need it. Do not warm it on page load. Do not warm it on scroll.

The checks worth making

Errors people can act on

Use the GOV.UK pattern. An error summary at the top with role='alert', a list of links that jump to the offending field, and a message tied to the input with aria-describedby. Then write the message like a human being.

Bad: Invalid file.

Better: That photo is 14 MB. We need it under 5 MB — most phones can shrink a photo for you when you share it.

Better still: The background behind you looks busy. Try standing in front of a plain, light-coloured wall.

Announce the checking state and the result through a polite live region. Don't yank focus. Don't turn the whole form red because one field failed.

Retrying without losing the form

This is the bug that generates the phone calls. The checker rejects the photo, something re-renders, the file input clears, and the address details the person spent four minutes typing are gone. They start again, or they ring the council.

Two rules. Keep form state in a plain object, not in the DOM. And if you need to put a file back onto an input — after a failed submission, say — use DataTransfer:

const dt = new DataTransfer();
dt.items.add(pendingFile);
input.files = dt.files;

That works in current browsers and saves you a world of pain. Also: never location.reload() to reset a form. React to the error, don't restart the session.

The no-JavaScript path is the real path

The client check is a courtesy. The form has to post to a server that validates the same rules and returns the same readable error summary, with the rest of the answers still filled in. If /js/photo-check.js is blocked by a corporate proxy, times out on a flaky connection, or throws on a photo the library has never seen, the form submits anyway. A validator that fails must never become a gate.

Give the check a hard deadline — ten seconds or so — and offer Continue without a check when it's slow. The server will catch what the browser missed, and the person behind the screen keeps moving.

One last bundle check

Run your build and look at where photo-check.js actually ended up. Nine times out of ten, a barrel file quietly pulls it into the shared chunk and every route on the site pays for it. That's the same dead weight you've hunted in the dist folder before — it just moved.

All Articles

Related Articles

Ask Before You Compare: A Tariff Widget That Waits Its Turn

Ask Before You Compare: A Tariff Widget That Waits Its Turn

Two Markets, One Bundle: Serving GB and NI Rules From a Config Loader

Two Markets, One Bundle: Serving GB and NI Rules From a Config Loader

Save-Data Is a Request, Not a Verdict: Serving Leaner Bundles Without Snobbery

Save-Data Is a Request, Not a Verdict: Serving Leaner Bundles Without Snobbery