Skip to content

Instantly share code, notes, and snippets.

@lewis-munyi
Created May 3, 2018 09:17
Show Gist options
  • Select an option

  • Save lewis-munyi/cf7b0a198ea23bb3d28bafc418a0b023 to your computer and use it in GitHub Desktop.

Select an option

Save lewis-munyi/cf7b0a198ea23bb3d28bafc418a0b023 to your computer and use it in GitHub Desktop.
PWA essentials

PWA essentials

All the things needed from service workers to manifests and opengraph descriptions

  • Copy this code into your app.js to install the service worker:
if ('serviceWorker' in navigator) {  //Check if browser supports service workers
    window.addEventListener('load', function () {
        navigator.serviceWorker.register('/serviceworker.js').then(function (registration) {
            // console.log("Registration was successful");
        }, function (err) {
            // console.log("registration failed :(", err);
        });
    });
}
  • Edit the content of the resources object in serviceworker.js and include the files you want cached or copy paste this code:
var CACHE_NAME = 'cache';
var resources = [
  '/images/logo.jpg',
  '/manifest.json',
  'index.html'
];

// Open + Cache + Verify cache
self.addEventListener('install', function(event) {
  // Perform install steps
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        // console.log('Opened cache');
        return cache.addAll(resources);
      })
  );
});

// Load cache if present otherwise install
self.addEventListener('fetch', function(event) {
    event.respondWith(
      caches.match(event.request)
        .then(function(response) {
          // Cache hit - return response
          if (response) {
            return response;
          }
          return fetch(event.request);
        }
      )
    );
  });
  • Edit the contents of the manifest.json to edit the manifest or copy this code into a file named manifest.json
{
"name": "name",
"short_name": "name",
"icons": [
    {
        "src": "",
        "sizes": "192x192",
        "type": "image/png"
    },
    {
        "src": "",
        "sizes": "256x256",
        "type": "image/png"
    }
],
"theme_color": "#FFFFFF",
"background_color": "#FFFFFF",
"display": "standalone",
"orientation": "portrait",
"start_url": "index.html"
}
  • Upload your logo to realfavicongenerator and get the respective icons
  • Copy the opengraph contents below and the respective code from the website above to your index.html
<title>...</title>
<meta property="og:title" content="" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://" />
<meta property="og:image" content="http://.../logo.jpg" />
<meta property="og:description" content="Description.." />
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#FF9800">

I would appreciate it if you visited my blog while you are at it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment