javascript - Cache Versioning on Progressive Web Apps -
what current best practice service worker caching?
after using service workers , caching number of projects, having bit of maintenance headache manage cached assets project.
in cases using static cache (most cause of our headache) , our sw.js code pretty standard , looks follows:
var cachename = 'v1:static'; // cache static assets during install phase self.addeventlistener('install', function (e) { e.waituntil( caches.open(cachename).then(function (cache) { return cache.addall([ './', './css/style.css', './css/vendor.css', './js/build/script.min.js', './js/build/vendor.min.js' ]).then(function () { self.skipwaiting(); }); }) ); }); self.addeventlistener('fetch', function (event) { event.respondwith( caches.match(event.request).then(function (response) { if (response) { // retrieve cache return response; } // fetch normal return fetch(event.request); }) ); });
the problems begin once release new version of our app , need invalidate cache user.
what methods recommended update cache? aware of sw-precache or developers manually update cachename variable (or perhaps through task-runner). there other alternatives? there way invalidate 1 file instead of entire cache?
thanks
i suggest assets assessment of project(s). determine static assets dynamic ones. once have determined pure static ones, precache it.
there 2 ways of doing this. 1) use sw-toolbox or 2) manually update version number of service worker file browser update it.
i know pain experiencing invalidating cache , everything. might want try/implement sw-toolbox.
sw-toolbox method
const offline_url = '/pages/offline/'; importscripts('sw-toolbox.js'); self.toolbox.precache([ <path_to_static_asset> 'manifest.json', offline_url, '/' ]); self.toolbox.router.default = self.toolbox.networkfirst; self.toolbox.router.get('/(.*)', function (req, vals, opts) { return self.toolbox.networkfirst(req, vals, opts) .catch(function (error) { if (req.method === 'get' && req.headers.get('accept').includes('text/html')) { return self.toolbox.cacheonly(new request(offline_url), vals, opts); } throw error; }); });
google service worker boilerplate - link
this 1 pretty straight forward. down side of @ every deployment, have update cache_version
service-worker installed update automatically.
take note there workbox also. havent played around yet methods outdated. descendant precache , toolbox
Comments
Post a Comment