Tags: advent

29

sparkline

Thursday, December 6th, 2018

Mistletoe Offline

This article first appeared in 24 Ways, the online advent calendar for geeks.

It’s 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, that’s why we make sure we’ve got nice 404 pages. It’s not that we want people to ever get served a File Not Found message, but we acknowledge that, despite our best efforts, it’s bound to happen sometime. Murphy’s Law, innit?

But there are some Murphyesque situations where even your lovingly crafted 404 page won’t 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 can—and will—go wrong.

I guess there’s nothing we can do about those particular situations, right?

Wrong!

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

If you’ve 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. There’s a step before that. Step zero. Get your site running on HTTPS, if it isn’t already. You won’t be able to use a service worker unless everything’s being served over HTTPS, which makes sense when you consider the awesome power that a service worker wields.

If you’re 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). Here’s an example of the custom offline page for this year’s Ampersand conference.

When you’re 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 user’s 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, I’m 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

I’m 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 powerful—and, let’s be honest, the creepiest—feature of a service worker. Once it has been installed, the service worker lurks on the user’s 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

Let’s 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 doesn’t work, try to find it in the cache,
  • But if that doesn’t work, and it’s a request for a web page, show the custom offline page instead.

Here’s how that translates into JavaScript:

// Whenever a file is requested
addEventListener('fetch', fetchEvent => {
  const request = fetchEvent.request;
  fetchEvent.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 what’s happening at each point in the code, I’ve written a whole book for you. It’s 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 you’re calling in to every page on your site, or add this in a script element at the end of every page’s 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. Don’t 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, you’re making sure that every request can be intercepted.

Go further!

Nicely done! You’ve made sure that if—no, when—a visitor can’t reach your website, they’ll 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 they’re 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 version—which would be blazingly fast—and 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 isn’t writing the code, it’s figuring out the steps you want to take. Once you’ve got those steps written out, then it’s a matter of translating them into JavaScript.

Inevitably there will be some obstacles along the way—usually it’s a misplaced curly brace or a missing parenthesis. Don’t be too hard on yourself if your code doesn’t work at first. That’s just Murphy’s Law in action.

Tuesday, December 4th, 2018

Mistletoe Offline ◆ 24 ways

They let me write a 24 Ways article again. Will they never learn?

This one’s a whirlwind tour of using a service worker to provide a custom offline page, in the style of Going Offline.

By the way, just for the record, I initially rejected this article’s title out of concern that injecting a Cliff Richard song into people’s brains was cruel and unusual punishment. I was overruled.

Monday, January 22nd, 2018

Seedship

A thoroughly enjoyable adventure game in your browser. You are the AI of a colony starship. Humanity’s future is in your hands.

Tuesday, December 5th, 2017

Welcome to Interactive Fiction: You’re a Wizard-Sniffing Pig - Atlas Obscura

The fascinating history of interactive fiction from adventure game to hypertext.

The split between parsers and hyperlinks reminds me of different approaches to chatbots: free text entry vs. constrained input.

Sunday, December 3rd, 2017

Friday, November 10th, 2017

Travel Oregon: The Game

Oregon Trail, updated for our times. There should be appreciably less dysentery in this game.

Monday, July 3rd, 2017

Wikipedia: The Text Adventure

You are on a website. There are exits to the north, south, east and west.

>...

Sunday, April 16th, 2017

Adventure

The Internet Archive is now hosting early Macintosh software emulated right in your browser. That means you can play Adventure: the source of subsequent text adventures, natural language parsing, and chatbots.

Colossal Cave Adventure (also known as ADVENT, Colossal Cave, or Adventure) is a text adventure game, developed originally in 1976, by Will Crowther for the PDP-10 mainframe. The game was expanded upon in 1977, with help from Don Woods, and other programmers created variations on the game and ports to other systems in the following years.

In the game, the player controls a character through simple text commands to explore a cave rumored to be filled with wealth.

Monday, April 4th, 2016

A Personal History of the Text Adventure – Read-Only Memory

Naomi Alderman:

The text adventure, like poetry, tends to attract a small band of devoted fans rather than hundreds of millions of casual players. And yet, those who care about writing know that they are where the form starts; and I can’t help feeling that videogames in general would be better if they took as much care over their words, and over their narratives, as text adventures do.

Sunday, March 9th, 2014

BBC Radio 4 Extra - The Hitchhiker’s Guide to the Galaxy - The Hitchhiker’s Guide to the Galaxy Game - 30th Anniversary Edition

One of the most fiendish user-unfriendly (but oh-so-witty) adventure games of all time is now online for you to enjoy with some added graphical flourishes.

Tuesday, July 2nd, 2013

A Silent Forest

Hypertext adventure.

Wednesday, December 19th, 2012

Text Adventure: Zork Creators Honored With Pioneer Award | Game|Life | Wired.com

This might well be the best thing Wired has ever published. I wish every article were in this format.

Tuesday, November 13th, 2012

YOU CHOSE WRONG

Documenting all the ways you could die in a choose-your-own-adventure book.

Saturday, August 4th, 2012

Twitter conversation with ftrain

Lance Arthur uses a tweet from Paul Ford as a starting point for a text adventure.

Thursday, March 1st, 2012

The Jason Scott Adventure | Glorious Trainwrecks

Download and play the Jason Scott Adventure — only you can help Jason save the internet!

Wednesday, December 14th, 2011

HTML5 and CSS3 Advent 2011

Here’s a geek advent calendar I missed. There are some great CSS techniques here.

Saturday, November 27th, 2010

Adfont Calendar 2010 | A free font every day from Fontdeck

It's a type drawer that's also an advent calendar. Responsive too. Check it every day between December 1st and 24th.

Thursday, December 10th, 2009

appvent calendar 2009 | every day a free iPhone game

A free iPhone/iPod Touch game for every day of advent.

Thursday, November 12th, 2009

cyoa

An in-depth study mapping all the permutations in "choose your own adventure" books.

Monday, January 26th, 2009

Champion of Guitars.z5 - Parchment

The text adventure version of Guitar Hero.