Sitemap
Booking.com Engineering

Software engineering at Booking.com

Progressive Web Apps with Service Workers

10 min readApr 21, 2016

--

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

--

--

Jesse Yang
Jesse Yang

Written by Jesse Yang

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

No responses yet