What are service workers?

It's a new API to enable offline Web apps. (Like AppCache but that doesn't suck.)

Three parts:

The Service Worker

A worker-like object that intercepts all network requests and lets you handle them in JavaScript.

The Fetch API

XHR revamped.

The Cache API

A simple cache for content retrieved from the Web (or generated), directly accessibly by the Service Worker.

Show me code


<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
        // scope defaults to "/*"
        navigator.serviceWorker.register("/service-worker.js").then(function(serviceWorker) {
            // To use the serviceWorker immediately,
            // you might call window.location.reload()


this.oninstall = function(e) {
    // Create a cache of resources.
    var resources = new Cache();
    var visited = new Cache();
    // Fetch them.
    ).then(function() {
        // Add caches to the global caches.
        return Promise.all([
            caches.set("v1", resources),
            caches.set("visited", visited)
this.onfetch = function(e) {
        // Check to see if request is found in cache
        caches.match(e.request).catch(function() {
            // It's not? Prime the cache and return the response.
            return caches.get("visited").then(function(visited) {
                return fetch(e.request).then(function(response) {
                    visited.put(e.request, response);
                    // Don't bother waiting, respond already.
                    return response;
        }).catch(function() {
            // Connection is down? Simply fallback to a pre-cached page.
            return caches.match("/fallback.html");

An great intro by Jake Archibald

When can I use it?

Current status of implementations can be found here.