Search code examples
progressive-web-appsservice-workerclient-hints

How to create offline apps with Service Worker and srcset?


I would like my app (a static web site) to run offline using a Service Worker. I can't see a way to do this without caching all the images from the srcset attribute. I can see how client hints would solve the problem but that apart is there a solution that would work without involving the server doing anything but serve requested files?

I can see perhaps how a Service Worker could calculate the image to request given the information in the img tag and a naming convention for images...

Has anyone tackled this problem, or thought about it at all?


Solution

  • For full srcset functionality you would have to cache all resolutions indeed.

    While the screen density may seem to be a fixed property of a device, it actually is dynamic, e.g. a smartphone can cast/airplay to a TV screen. On desktops with multiple displays (e.g. Retina MacBook with an external display) screen resolution may change when the browser window is moved around. All these changes may happen offline long after you've done caching, so you can't know for sure which resolutions will be picked.

    A simple solution is to always use 2x images for everything. Higher DPI makes image distortions less noticeable, so you can compress them more heavily to offset the cost of higher resolution.

    Another solution is to catch loading errors on images and replace srcset with image URL that you know is cached. BTW: you may need to add onerror="…" in the markup, because the error may fire before any other scripts had chance to run on the page yet, or before adding error handlers programmatically check all image elements for img.complete && !img.naturalWidth to detect missed error events.