How does SW-Precache works

Xuan Huang
Mar 28, 2017 · 7 min read

Overview

service-worker.tmpl
lib/
├ sw-precache.js
└ functions.js

Initialization

// service-worker.tmpl
var precacheConfig = <%= precacheConfig %>;
// sw.js
var precacheConfig = [
["js/a.js", "3cb4f0"],
["css/b.css", "c5a951"]
]
> urlToCacheKeys
< Map(2) {
"http.../js/a.js" => "http.../js/a.js?_sw-precache=3cb4f0",
"http.../css/b.js" => "http.../css/b.css?_sw-precache=c5a951"
}

On Install

On Activate

// sw.js
existingRequests.map(function(existingRequest) {
if (!setOfExpectedUrls.has(existingRequest.url)) {
return cache.delete(existingRequest);
}
})

On Fetch

Should Respond?

// sw.js*
var url = event.request.url
shouldRespond = urlsToCacheKeys.has(url);

Navigation Fallback

Respond from Cache

// sw.js*
event.respondWith(
caches.open(cacheName).then(cache => {
return cache.match(urlsToCacheKeys.get(url))
.then(response => {
if (response) return response;
});
})
);

Cache Management Recap

The first build

// cachedUrls
Set(0) {}
// urlToCacheKeys
Map(2) {
"http.../js/a.js" => "http.../js/a.js?_sw-precache=3cb4f0",
"http.../css/b.js" => "http.../css/b.css?_sw-precache=c5a951"
}
// SW Network Logs
[sw] GET a.js?_sw-precache=3cb4f0
[sw] GET b.css?_sw-precache=c5a951
// cachedUrls
Set(2) {
"http.../js/a.js?_sw-precache=3cb4f0",
"http.../css/b.css?_sw-precache=c5a951"
}
// urlToCacheKeys
Map(2) {
"http.../js/a.js" => "http.../js/a.js?_sw-precache=3cb4f0",
"http.../css/b.js" => "http.../css/b.css?_sw-precache=c5a951"
}
// SW Network Logs
// Empty

The second build

// cachedUrls
Set(2) {
"http.../js/a.js?_sw-precache=3cb4f0",
"http.../css/b.css?_sw-precache=c5a951"
}
// urlToCacheKeys
Map(2) {
"http.../js/a.js" => "http.../js/a.js?_sw-precache=d6420f",
"http.../css/b.js" => "http.../css/b.css?_sw-precache=c5a951"
}
// SW Network Logs
[sw] GET a.js?_sw-precache=d6420f
// what's in cache?
http.../js/a.js?_sw-precache=3cb4f0
http.../js/a.js?_sw-precache=d6420f
http.../css/b.css?_sw-precache=c5a951
// existingRequests
http.../js/a.js?_sw-precache=3cb4f0
http.../js/a.js?_sw-precache=d6420f
http.../css/b.css?_sw-precache=c5a951
// setOfExpectedUrls
Set(2) {
"http.../js/a.js?_sw-precache=d6420f",
"http.../css/b.css?_sw-precache=c5a951"
}
// the one deleted
http.../js/a.js?_sw-precache=3cb4f0

Conclusions

Precaching is NOT free

“App Shell”

This is not the end

Thanks to Yi Yang

Xuan Huang

Written by

Team Web. Worked at Facebook, Alibaba, WePiao.com, Ele.me. Spoke at JSConfCN, QCon, GDG.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade