This is a simple module that provides a Service Worker for viewing Processwire pages offline. It’s heavily based on the work of Jeremy Keith – thank you Jeremy!
When a people visit your site and their browser supports the use of service workers, a small JavaScript (the service worker) gets installed in their browser. The script sits in the background, intercepts network requests and then does the following:
If the requested resource is an HTML document:
- try and fetch the page from the network
- if that doesn’t work, try and serve the page from the cache
- if that also fails, fall back to a specified offline page
If the requested resource is a file:
- try and serve the file from the cache (if available)
- if the file is not in the cache, try and request it from the network
- if everything else fails and the requested file is an image, show a placeholder
Copy the module directory to /site/modules/, then in Processwire Admin go to Modules > Site > Add New, click “Refresh” and install the ServiceWorker module.
During the installation, the module copies a PHP file (serviceworker.js.php
) to your Processwire root directory. This file is served as JavaScript and contains the actual Service Worker.
The module offers a few configuration options:
- Current cache version: cache version number. You can force the service worker to upgrade the cached pages and static assets by bumping this to a higher number. Also, the module bumps the version automatically when one of the configured offline pages is saved.
- Max. pages in cache: the number of pages that can live in the page cache
- Max. images in cache: the number of images that can live in the image cache
- Offline page: a page that is served when the user agent has no connection to the network.
- Additional pages to cache: other pages that are cached upfront when the service worker gets installed.
- Static assets to cache: any static assets that need to be cached when the service worker gets installed.
To include the service worker in your templates use
<?php $modules->get('ServiceWorker')->renderJavaScript(); ?>
.
Right before the closing </body>
tag is a good place to put it.
Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication