[Part 2] Get rapid offline capability in your Angular app with service worker

How to store external API responses to decrease page response time
Getting external API data to cache on your site

Continuation

Welcome back, if you haven’t checked out the last article on setting up static asset caching do this here: [Part 1]

Dynamic asset caching

When you have external API links such as to Wordpress, Googleapis (fonts) or a CDN their may be responses you wish to cache for a period (> day, week etc) such that the user doesn’t spend time downloading old content.

Blogs and fonts

In my case this example I pulled blogs from a Wordpress site and several fonts from fonts.google.com, but these can’t be pre-cached because they don’t pre-exist in the /dist folder of your app.

For speed and ease of use, we will use a library called sw-toolbox to handle our dynamic content caching:

npm install sw-toolbox

Importing the new scripts

First we need to create our config file at sw-config/sw-toolbox-config.js and include it in our gulpfile.js

# File: gulpfile.js
gulp.task('sw-build', function() {
...
gulp.watch('./sw-config/sw-toolbox-config.js', ['sw-generate']);
});
gulp.task('sw-generate', ()=>{
...
swPrecache.write(
...,
...,
() => {
# Copies the script to the distribution and inlcudes 
# the sw-toolbox module in the build
gulp.src('sw-config/sw-toolbox-config.js')
.pipe(gulp.dest('dist'));
gulp.src('node_modules/sw-toolbox').pipe(gulp.dest('dist'));
gutil.log("[gulpfile] Task completed!:");
});
});

Importantly we will also need to include the sw-toolbox-config.js script in our sw-precache-config.js as an import to ensure its included in the service worker:

# File: sw-config/sw-precache-config.js
module.exports = {
...,
staticFileGlobs: [
...,
],
“importScripts”: [
“sw-toolbox.js”,
“sw-toolbox-config.js”
]
};

Configuring sw-toolbox routes

The routes you want to cache can be found through the network tab, in my case they were as follows:

Request urls for blogs and fonts

They return blogs posts and fonts necessary for my site (obviously), but the fonts are never going to change and the blogs will probably get updated once every 3 days to a week. Definitely not the content a user on a slow GPRS phone connection wants to download!

Open the sw-toolbox-config.js script to configure:

# This will be ok when imported into the dist folder
importScripts(“sw-toolbox.js”);
console.log(“Toolbox running: “);
toolbox.options.debug = true;

First we will need to import the sw-toolbox script which sadly has to be copied manually into the /dist folder as we can’t access node_modules in the bundle. Next I have turned on debug mode which displays information under the inspect option at application -> service-worker -> inspect whilst sw.js is installing.

toolbox.router.get(/https:\/\/.*public-api.wordpress.com\/.*$/, toolbox.cacheFirst, {
cache: {
name: ‘wordpressapi’,
maxEntries: 10,
maxAgeSeconds: 604800
}
});

Here I have defined our first route, specifying any path that begins with https:// + any characters + (followed by) public-api.wordpress.com/ + any characters + end of url. Its a regex which I wrote with the help of : https://regex101.com a great learning and debugging tool.

Next I set the maxAge to 7 days and defined the caching strategy handler from one of the built ins available; cacheFirst which checks if the entry already exists in the browser cache. I set the max entries to 10 so we don’t chew up user storage space

toolbox.router.get(/https:\/\/.*files.wordpress.com.*$/, toolbox.fastest, {
cache: {
name: ‘wordpressfiles’,
maxEntries: 100,
}
});
toolbox.router.get(/^https:\/\/.*googleapis\.com\/.*/, toolbox.cacheFirst, {
cache: {
name: ‘googleapis’,
maxEntries: 10
}
});

Next I repeated the same process for Wordpress image resources (using the fastest strategy, which tries both cache and network and only returns one), and finally the fonts (setting maxEntries to 10, because something is definitely wrong if I that many!).

All done!

Make sure gulp sw-build is still running and save your file. You should now see your assets being cached offline! (Remember to npm run static-serve)

Leave comments and recommends down below!

Thanks for reading!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.