Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 4, 2018 12:00 pm GMT

Mistletoe Offline

Jeremy Keith reminds us that 4G is king. The carollers sing. One tunnel has passed, a new ones beginning. Dreams of wi-fi on the go. Fingers numb, smart phones aglow. Its Christmas time, mistletoe offline. Children streaming their gameplay online. With batteries on fire and gigabytes for free, its time to rejoice in connectivity.


Its that time of year, when we gather together as families to celebrate the life of the greatest person in history. This man walked the Earth long before us, but he left behind words of wisdom. Those words can guide us every single day, but they are at the forefront of our minds during this special season.

I am, of course, talking about Murphy, and the golden rule he gave unto us:

Anything that can go wrong will go wrong.

So true! I mean, thats why we make sure weve got nice 404 pages. Its not that we want people to ever get served a File Not Found message, but we acknowledge that, despite our best efforts, its bound to happen sometime. Murphys Law, innit?

But there are some Murphyesque situations where even your lovingly crafted 404 page wont help. What if your web server is down? What if someone is trying to reach your site but they lose their internet connection? These are all things than canand willgo wrong.

I guess theres nothing we can do about those particular situations, right?

Wrong!

A service worker is a Murphy-battling technology that you can inject into a visitors device from your website. Once its installed, it can intercept any requests made to your domain. If anything goes wrong with a requestas is inevitableyou can provide instructions for the browser. Thats your opportunity to turn those server outage frowns upside down. Take those network connection lemons and make network connection lemonade.

If youve got a custom 404 page, why not make a custom offline page too?

Get your server in order

Step one is to make …actually, wait. Theres a step before that. Step zero. Get your site running on HTTPS, if it isnt already. You wont be able to use a service worker unless everythings being served over HTTPS, which makes sense when you consider the awesome power that a service worker wields.

If youre developing locally, service workers will work fine for localhost, even without HTTPS. But for a live site, HTTPS is a must.

Make an offline page

Alright, assuming your site is being served over HTTPS, then step one is to create an offline page. Make it as serious or as quirky as is appropriate for your particular brand. If the website is for a restaurant, maybe you could put the telephone number and address of the restaurant on the custom offline page (unsolicited advice: you could also put this on the home page, you know). Heres an example of the custom offline page for this years Ampersand conference.

When youre done, publish the offline page at suitably imaginative URL, like, say /offline.html.

Pre-cache your offline page

Now create a JavaScript file called serviceworker.js. This is the script that the browser will look to when certain events are triggered. The first event to handle is what to do when the service worker is installed on the users device. When that happens, an event called install is fired. You can listen out for this event using addEventListener:

addEventListener('install', installEvent => {// put your instructions here.}); // end addEventListener

In this case, you want to make sure that your lovingly crafted custom offline page is put into a nice safe cache. You can use the Cache API to do this. You get to create as many caches as you like, and you can call them whatever you want. Here, Im going to call the cache Johnny just so I can refer to it as JohnnyCache in the code:

addEventListener('install', installEvent => {  installEvent.waitUntil(    caches.open('Johnny')    .then( JohnnyCache => {      JohnnyCache.addAll([       '/offline.html'      ]); // end addAll    }) // end open.then  ); // end waitUntil}); // end addEventListener

Im betting that your lovely offline page is linking to a CSS file, maybe an image or two, and perhaps some JavaScript. You can cache all of those at this point:

addEventListener('install', installEvent => {  installEvent.waitUntil(    caches.open('Johnny')    .then( JohnnyCache => {      JohnnyCache.addAll([       '/offline.html',       '/path/to/stylesheet.css',       '/path/to/javascript.js',           '/path/to/image.jpg'      ]); // end addAll    }) // end open.then  ); // end waitUntil}); // end addEventListener

Make sure that the URLs are correct. If just one of the URLs in the list fails to resolve, none of the items in the list will be cached.

Intercept requests

The next event you want to listen for is the fetch event. This is probably the most powerfuland, lets be honest, the creepiestfeature of a service worker. Once it has been installed, the service worker lurks on the users device, waiting for any requests made to your site. Every time the user requests a web page from your site, a fetch event will fire. Every time that page requests a style sheet or an image, a fetch event will fire. You can provide instructions for what should happen each time:

addEventListener('fetch', fetchEvent => {// What happens next is up to you!}); // end addEventListener

Lets write a fairly conservative script with the following logic:

  • Whenever a file is requested,
  • First, try to fetch it from the network,
  • But if that doesnt work, try to find it in the cache,
  • But if that doesnt work, and its a request for a web page, show the custom offline page instead.

Heres how that translates into JavaScript:

// Whenever a file is requestedaddEventListener('fetch', fetchEvent => {  const request = fetchEvent.request;  request.respondWith(    // First, try to fetch it from the network    fetch(request)    .then( responseFromFetch => {      return responseFromFetch;    }) // end fetch.then    // But if that doesn't work    .catch( fetchError => {      // try to find it in the cache      caches.match(request)      .then( responseFromCache => {        if (responseFromCache) {         return responseFromCache;       // But if that doesn't work       } else {         // and it's a request for a web page         if (request.headers.get('Accept').includes('text/html') {           // show the custom offline page instead           return caches.match('/offline.html');         } // end if       } // end if/else     }) // end match.then   }) // end fetch.catch  ); // end respondWith}); // end addEventListener

I am fully aware that I may have done some owl-drawing there. If you need a more detailed breakdown of whats happening at each point in the code, Ive written a whole book for you. Its the perfect present for Murphymas.

Hook up your service worker script

You can publish your service worker script at /serviceworker.js but you still need to tell the browser where to look for it. You can do that using JavaScript. Put this in an existing JavaScript file that youre calling in to every page on your site, or add this in a script element at the end of every pages HTML:

if (navigator.serviceWorker) {  navigator.serviceWorker.register('/serviceworker.js');}

That tells the browser to start installing the service worker, but not without first checking that the browser understands what a service worker is. When it comes to JavaScript, feature detection is your friend.

You might already have some JavaScript files in a folder like /assets/js/ and you might be tempted to put your service worker script in there too. Dont do that. If you do, the service worker will only be able to handle requests made to for files within /assets/js/. By putting the service worker script in the root directory, youre making sure that every request can be intercepted.

Go further!

Nicely done! Youve made sure that ifno, whena visitor cant reach your website, theyll get your hand-tailored offline page. You have temporarily defeated the forces of chaos! You have briefly fought the tide of entropy! You have made a small but ultimately futile gesture against the inevitable heat-death of the universe!

This is just the beginning. You can do more with service workers.

What if, every time you fetched a page from the network, you stored a copy of that page in a cache? Then if that person tries to reach that page later, but theyre offline, you could show them the cached version.

Or, what if instead of reaching out the network first, you checked to see if a file is in the cache first? You could serve up that cached versionwhich would be blazingly fastand still fetch a fresh version from the network in the background to pop in the cache for next time. That might be a good strategy for images.

So many options! The hard part isnt writing the code, its figuring out the steps you want to take. Once youve got those steps written out, then its a matter of translating them into JavaScript.

Inevitably there will be some obstacles along the wayusually its a misplaced curly brace or a missing parenthesis. Dont be too hard on yourself if your code doesnt work at first. Thats just Murphys Law in action.


About the author

Jeremy Keith lives in Brighton, England where he makes websites with the splendid design agency Clearleft. You may know him from such books as DOM Scripting, Bulletproof Ajax, HTML5 For Web Designers, Resilient Web Design, and, most recently, Going Offline.


He curated the dConstruct conference for a number of years as well as Brighton SF, and he organised the world’s first Science Hack Day. He also made the website Huffduffer to allow people to make podcasts of found soundsit’s like Instapaper for audio files.


Hailing from Erin’s green shores, Jeremy maintains his link to Irish traditional music running the community site The Session. He also indulges a darker side of his bouzouki-playing in the band Salter Cane.


Jeremy spends most of his time goofing off on the internet, documenting his time-wasting on adactio.com, where he has been writing for over fifteen years.

More articles by Jeremy


Original Link: http://feedproxy.google.com/~r/24ways/~3/CeXwkQ0CDNM/

Share this article:    Share on Facebook
View Full Article

24 Ways

# 24 ways is an edgeofmyseat.com production. # Edited by Drew McLellan and Brian Suda. # Assisted by Anna Debenham and Owen Gregory.

More About this Source Visit 24 Ways