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

How to store external API responses to decrease page response time

Image for post
Image for post
Getting external API data to cache on your site


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.jsgulp.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
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.jsmodule.exports = {
staticFileGlobs: [
“importScripts”: [

Configuring sw-toolbox routes

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

Image for post
Image for post
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
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)

Image for post
Image for post

Leave comments and recommends down below!

Thanks for reading!

Image for post
Image for post

UCD Statistics & ACM, Learning Data Science, Winning Team @ Citadel Dublin Data Open. www.hugodolan.com/linkedin | Mailing List: http://eepurl.com/gkV7ov

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store