mistadikay
1/12/2016 - 3:17 PM

Code for the article How to Make Your Blog Work Offline: https://blog.redradix.com/how-to-make-your-blog-work-offline

Code for the article How to Make Your Blog Work Offline: https://blog.redradix.com/how-to-make-your-blog-work-offline

// 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 = [
  '/assets/css/screen.css',
  '/assets/js/index.js',
  '/content/images/2015/12/bg-blox.jpg'
];

self.addEventListener('install', function(event) {
  // waitUntil() ensures that the Service Worker will not
  // install until the code inside has successfully occurred
  event.waitUntil(
    // Create cache with the name supplied above and
    // return a promise for it
    caches.open(cacheName).then(function(cache) {
      // Add assets supplied above
      cache.addAll(assetsToCache);
      // Get your blog's pages and add them to cache
      cachePages(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
    cache.addAll(urls);
  });
}

// Simple function to get multiple matched groups
function getMatches(string, regex) {
  var matches = [];
  var match;
  while (match = regex.exec(string)) {
    matches.push(match[1]);
  }
  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; }
  event.respondWith(
    // Open the cache created when install
    caches.open(CACHE_NAME).then(function(cache) {
      // 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);
      })
    })
  );
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <script>
    // 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);
      });
    }
  </script>
</body>
</html>