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

/index.html

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

/service-worker.js

this.oninstall = function(e) {
    // Create a cache of resources.
    var resources = new Cache();
    var visited = new Cache();
    // Fetch them.
    e.waitUntil(resources.add(
        "/index.html",
        "/fallback.html",
        "/css/base.css",
        "/js/app.js",
        "/img/logo.png"
    ).then(function() {
        // Add caches to the global caches.
        return Promise.all([
            caches.set("v1", resources),
            caches.set("visited", visited)
        ]);
    }));
};
 
this.onfetch = function(e) {
    e.respondWith(
        // 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.