Service Worker Caching Strategies Based on Request Types

Thomas Steiner
Aug 20, 2018 · 5 min read

TL;DR

Different Caching Strategies for Different Types of Resources

URL-based Determination of the Request Type

// In serviceworker.js
self.addEventListener('fetch', (event) => {
// Parse the URL
const requestURL = new URL(event.request.url);
// Handle article URLs
if (/^\/article\//.test(requestURL.pathname)) {
event.respondWith(/* some response strategy */);
return;
}
if (/\.webp$/.test(requestURL.pathname)) {
event.respondWith(/* some other response strategy */);
return;
}
/* … */
});

Request.destination-based Determination of the Request Type

Request.destination playground app showing different request types
An <img>, two <p>s with background images and triggers for XMLHttpRequest or fetch(), an <iframe>, and a <video> with poster image and timed text track
// In serviceworker.js
self.addEventListener('fetch', (event) => {
const destination = event.request.destination;
switch (destination) {
case 'style':
case 'script':
case 'document':
case 'image': {
event.respondWith(
/* "Network Falling Back to Cache" strategy */);
return;
}
case 'font': {
event.respondWith(/* "Cache Only" strategy */);
return;
}
// All `XMLHttpRequest` or `fetch()` calls where
// `Request.destination` is the empty string default value
default: {
event.respondWith(/* "Network Only" strategy */);
return;
}
}
});

Browser Support for Request.destination

When Request.destination isn’t Enough

Conclusion

Acknowledgements

Dev Channel

Developers Channel - the thoughts, opinions and musings from members of the Chrome team.

Thomas Steiner

Written by

Web Developer Advocate at Google

Dev Channel

Developers Channel - the thoughts, opinions and musings from members of the Chrome team.