Progressive Web Apps with Service Workers

In this post we will discuss Progressive Web Apps and Service Workers. How can they help modern-day mobile web users, and how are we experimenting with them at Booking.com? We will share some challenges we’ve encountered, as well as some of our learnings.

Jesse Yang
Apr 21, 2016 · 10 min read

What is a Progressive Web App?

What is a Service Worker?

Quick Facts

Browser support

What can Service Workers do?

Service Workers in Action

Registration

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js', { scope: './' }).then(function() {
if (navigator.serviceWorker.controller) {
console.log('The service worker is currently handling network operations.');
} else {
console.log('Failed to register.');
}
});
}
navigator.serviceWorker.register('/scripts/service-worker.js', { scope: '/' })
Server {

listen www.example.com:443 ssl;

...

location /scripts/service-worker.js {
add_header 'Service-Worker-Allowed' '/';
}
}

Inside the worker

Service Workers at Booking.com

Caching Strategy Examples

toolbox.router.get(/static\/(css|js|images|img)\//,
toolbox.cacheFirst, {
cache: { name: 'static-files' }
}
);
toolbox.router.get(/\/(confirmation|mybooking|myreservations)/i, 
toolbox.networkFirst, {
networkTimeoutSeconds: 10,
cache: { name: 'booking-confirm' }
}
);
toolbox.router.any(/www.google-analytics.com/, toolbox.networkOnly);

Local Shortcuts

toolbox.router.get("/confirmations/(.*)", function(request, values, options) {
var url = request.url;
var promise = toolbox.networkFirst(request, values, options);
var confirmationId = values[0];
if (confirmationId) {
// when the request finishes
promise.then(function(response) {
if (!response || response.status !== 200) return;
self.caches.open('last-confirmation').then(function(cache) {
// save a 302 Redirect response to "/confirmation"
var redirectResponse = new Response('Redirecting', {
status: 302,
statusText: 'Found',
headers: {
Location: url
}
});
cache.put('/confirmation', redirectResponse);
});
});
}
return promise;
}, {
networkTimeoutSeconds: 10,
cache: {
name: 'confirmations',
}
});

toolbox.router.get('/confirmation', toolbox.cacheOnly, {
cache: {
name: 'last-confirmation'
}
});

The Secure Domain Problem

Final Thoughts

Resources

Booking.com Development

Software development at Booking.com

Booking.com Development

Software development at Booking.com

Jesse Yang

Written by

Always fascinated by people, although I don’t like interacting with them much.

Booking.com Development

Software development at Booking.com