Our industry is abuzz with talk about Progressive Web Apps (PWAs) and with good reason: they are a great way to improve the experiences our users have on our sites, especially when it comes to performance. Using Service Workers—a key component of PWAs—we can manage network requests and the cache to an incredibly granular degree. We can also totally abuse the privilege Service Workers grant us when it comes to writing files to disk.
In this session, Aaron Gustafson will discuss some of the potential pitfalls in implementing Service Workers, especially when it comes to managing heavy files like images and video. He’ll provide guidance on current best practices in cache management. And he’ll offer a few simple recipes you can put to use right away to deliver amazing experiences for your users that respect their data usage and disk space.
28. @AaronGustafson
Registering a Service Worker
if ( "serviceWorker" in navigator ) {
navigator.serviceWorker.register( "/serviceworker.min.js" );
}
Path is important!
59. @AaronGustafson
#6: Respect Save Data
58
let save_data = false;
if ( 'connection' in navigator ) {
save_data = navigator.connection.saveData;
}
aka.ms/ag-sw
60. @AaronGustafson
#6: Respect Save Data
59
self.addEventListener( "fetch", event => {
const request = event.request,
url = request.url;
if ( request.headers.get("Accept").includes("image") ) {
event.respondWith(
if ( save_data ) {
return respondWithFallbackImage( url );
}
// …
);
}
aka.ms/ag-sw
72. @AaronGustafson
#8: Clean up after yourself
71
if ( "serviceWorker" in navigator ) {
navigator.serviceWorker.register( "/serviceworker.min.js" );
if ( navigator.serviceWorker.controller ) {
window.addEventListener( "load", function(){
navigator.serviceWorker.controller.postMessage( "clean up" );
});
}
}
aka.ms/ag-sw
73. @AaronGustafson
#8: Clean up after yourself
72
addEventListener("message", messageEvent => {
if (messageEvent.data == "clean up") {
for ( let key in sw_caches ) {
if ( sw_caches[key].limit != undefined ) {
trimCache( sw_caches[key].name, sw_caches[key].limit );
}
}
}
});
aka.ms/ag-sw
74. @AaronGustafson
#8: Clean up after yourself
73
addEventListener("message", messageEvent => {
if (messageEvent.data == "clean up") {
for ( let key in sw_caches ) {
if ( sw_caches[key].limit != undefined ) {
trimCache( sw_caches[key].name, sw_caches[key].limit );
}
}
}
});
aka.ms/ag-sw
75. @AaronGustafson
Make good choices
1. No animated GIFs (especially as backgrounds)
2. Use responsive images
3. Lazy load images
4. Provide alternate image formats
5. Provide fallback images via Service Worker
6. Pay attention to the Save Data header
7. Prioritize certain images
8. Clean up after yourself
74