Detecting image requests in service workers

In Going Offline, I dive into the many different ways you can use a service worker to handle requests. You can filter by the URL, for example; treating requests for pages under /blog or /articles differently from other requests. Or you can filter by file type. That way, you can treat requests for, say, images very differently to requests for HTML pages.

One of the ways to check what kind of request you’re dealing with is to see what’s in the accept header. Here’s how I show the test for HTML pages:

if (request.headers.get('Accept').includes('text/html')) {
    // Handle your page requests here.

So, logically enough, I show the same technique for detecting image requests:

if (request.headers.get('Accept').includes('image')) {
    // Handle your image requests here.

That should catch any files that have image in the request’s accept header, like image/png or image/jpeg or image/svg+xml and so on.

But there’s a problem. Both Safari and Firefox now use a much broader accept header: */*

My if statement evaluates to false in those browsers. Sebastian Eberlein wrote about his workaround for this issue, which involves looking at file extensions instead:

if (request.url.match(/\.(jpe?g|png|gif|svg)$/)) {
    // Handle your image requests here.

So consider this post a patch for chapter five of Going Offline (page 68 specifically). Wherever you see:

if (request.headers.get('Accept').includes('image'))

Swap it out for:

if (request.url.match(/\.(jpe?g|png|gif|svg)$/))

And feel to add any other image file extensions (like webp) in there too.

Have you published a response to this? :


Šime Vidas

This is one of the examples of why the service worker API is too low level for me, and why I plan to just use workbox instead; micro-managing requests like that seems too intricate and error-prone for the average developer

Ben Kelly

Soon it should be possible to check for images with evt.request.destination === 'image'. Ships in FF61 release next week. Already available in other browsers, AFAIK.

# Posted by Ben Kelly on Wednesday, June 20th, 2018 at 2:27pm

Previously on this day

4 years ago I wrote 100 words 087

Day eighty seven.

5 years ago I wrote Responsive Day Out 2: The Scheduling

Everything you need to know about your trip to the seaside.

6 years ago I wrote Battle for the planet of the APIs

API shall not kill API.

9 years ago I wrote So

Such a little word.

12 years ago I wrote Hacktime

The hackclock is ticking.

12 years ago I wrote Hacknight

Hackery, Werewolf and The Doctor.

15 years ago I wrote Blooming wit

Yesterday was Bloomsday. I wasn’t in Dublin: I was on stage in Brighton with Salter Cane. Still, I couldn’t let the occasion pass unmarked.

16 years ago I wrote Browser gloom and doom

When I wrote earlier this month about Microsoft’s decision to stagnate browser development, I took a fairly pessimistic view of where we developers now stand.