Service-worker force update of new assets

。_饼干妹妹 提交于 2019-11-29 22:53:35

One option is just to use a the service worker's cache as a fallback, and always attempt to go network-first via a fetch(). You lose some performance gains that a cache-first strategy offers, though.

An alternative approach would be to use sw-precache to generate your service worker script as part of your site's build process.

The service worker that it generates will use a hash of the file's contents to detect changes, and automatically update the cache when a new version is deployed. It will also use a cache-busting URL query parameter to ensure that you don't accidentally populate your service worker cache with an out-of-date version from the HTTP cache.

In practice, you'll end up with a service worker that uses a performance-friendly cache-first strategy, but the cache will get updated "in the background" after the page loads so that the next time it's visited, everything is fresh. If you want, it's possible to display a message to the user letting them know that there's updated content available and prompting them to reload.

One way of invalidating the cache would be to bump version of the CACHE_NAME whenever you change anything in the cached files. Since that change would change the service-worker.js browser would load a newer version and you'd have a chance to delete the old caches and create new ones. And you can delete the old cache in the activate handler. This is the strategy described in prefetch sample. If you already using some kind of version stamps on CSS files make sure that they find their way into service worker script.

That of course does not change the fact that cache headers on CSS file need to be set correctly. Otherwise service worker will just load the file that is already cached in browser cache.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!