Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Code for the article How to Make Your Blog Work Offline:
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
// Test if service workers are supported
if ('serviceWorker' in navigator) {
// Attempt to register it
navigator.serviceWorker.register('/sw.js').then(function() {
// Success
console.log('ServiceWorker registration successful');
}).catch(function(err) {
// Fail
console.log('ServiceWorker registration failed: ', err);
// You have to supply a name for your cache, this will
// allow us to remove an old one to avoid hitting disk
// space limits and displaying old resources
var cacheName = 'v1';
// Change for your sitemap's path if that's what
// you'll use to get your blog's pages
var sitemapUrl = '/sitemap.xml';
// Replace with your assets paths
var assetsToCache = [
self.addEventListener('install', function(event) {
// waitUntil() ensures that the Service Worker will not
// install until the code inside has successfully occurred
// Create cache with the name supplied above and
// return a promise for it {
// Add assets supplied above
// Get your blog's pages and add them to cache
function cachePages(cache) {
// Get sitemap and return the text response
fetch(sitemapUrl).then(function(response) {
return response.text();
}).then(function(text) {
// Regex to match xml locations (URLs)
var pattern = /<loc>(.+?)</g;
// Get all matches within the text
var urls = getMatches(text, pattern);
// Add them to the previously opened cache
// Simple function to get multiple matched groups
function getMatches(string, regex) {
var matches = [];
var match;
while (match = regex.exec(string)) {
return matches;
self.addEventListener('fetch', function(event) {
// Ignore non-get request like when accessing the admin panel
if (event.request.method !== 'GET') { return; }
// Don't try to handle non-secure assets because fetch will fail
if (/http:/.test(event.request.url)) { return; }
// Open the cache created when install {
// Go to the network to ask for that resource
return fetch(event.request).then(function(networkResponse) {
// Add a copy of the response to the cache (updating the old version)
cache.put(event.request, networkResponse.clone());
// Respond with it
return networkResponse;
}).catch(function() {
// If there is no internet connection, try to match the request
// to some of our cached resources
return cache.match(event.request);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment