Basil: Secret Santa as a Service | Trys Mudford
Trys writes up the process—and the tech (JAM)stack—he used to build basil.christmas.
Trys writes up the process—and the tech (JAM)stack—he used to build basil.christmas.
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?
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.
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
.
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.
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:
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.
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.
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.
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.
Kate has been hand-making Christmas cards for seventeen years.
2013’s Gizmo Stardust remains my favourite.
I like Erin’s list.
I had exactly the same resistance to Instagram as Dan and I had exactly the same Yuletide conversion.
Perfect seasonal entertainment. Perfect.
A very cute Christmas message from Torchbox.
He sees you when you are sleeping. He knows when you are awake. Be afraid. Be very afraid. And be good ...for goodness sake.
On the tenth day of Newton, My true love gave to me, Ten drops of genius, Nine silver co-oins, Eight circling planets, Seven shades of li-ight, Six counterfeiters, Cal-Cu-Lus! Four telescopes, Three Laws of Motion, Two awful feuds, And …
Christmas letters to Christopher Walken.
My family is in Ireland. Jessica’s family is in Arizona. We live in Brighton.
Every Christmas, we take it in turn to visit one of our families; Ireland one year, Arizona the next. Last year we were going to go to Ireland but because of a beaureaucratic incident with Jessica’s passport, we ended up having our first Christmas in Brighton and my mother came over from Ireland to visit us instead.
It was a great Christmas but it kind of messed up our scoring system. What are we supposed to do this year? Is Ireland still due for the next visit or was last year a de-facto Irish Christmas? Oh, what a conundrum!
I think we’ve found the perfect answer. We’re going to Arizona but we’re bringing my mother over with us. She showed up in Brighton today. Tomorrow we make the long trip across the Atlantic: Brighton to Gatwick, Gatwick to Houston, Houston to Tucson, Tucson to Sierra Vista. The shortest day of the year is actually going to be very long indeed for us.
Once the traveling is done, I aim to spend the holiday season being slothful and indolent in the high desert. Doing absolutely nothing—it’s what Christmas is all about.
Yours to cut out and keep.
An utterly addictive old-school platform game in Flash to get you in the mood for Christmas.
The definitive response to continuous partial Christmas.
I just celebrated my first Christmas in Brighton. I usually spend the holiday season either in Ireland with my family or in Arizona with Jessica’s family. This year, thanks to a Kafkaesque game of beaureaucratic tag involving the Home Office and Jessica’s passport, we were stranded in the UK—like most people as it turned out.
It ended up being a most pleasant affair, spent in the company of good friends and copious amounts of good food. Following a shady rendez-vous with chicken-pimp Pete, we had the raw materials for an excellent roast. After an evening (and early morning) of playing poker, in which Andy emerged victorious, the festivities were complete.
With Christmas done, I am now going to spend my first New Year’s Eve in Brighton. To be honest, I’m not much of a party-goer so I don’t think I’ll be enduring the cold for Fatboy Slim. Besides, my mother is coming over to visit and I don’t think that would be her scene either.
Instead, I’m planning to carry my current enjoyment of coziness, comfort food and mindless entertainment across the threshold of the year. The entertainment will be delivered via the big screen TV that I treated myself with at Christmas.
Now I can finally watch those films that I vowed only ever to watch on a big screen:
If you need me, I’ll be busy treasuring the twin spirits of Christmas present: gluttony and sloth. Once the new year has been rung in, they can go back to being vices but for now they are both most assuredly virtues.
A behind-the-scenes look at a Christmas tradition. I always suspected as much.