Skip to content

Commit c352213

Browse files
committed
clean old asset + new sw
1 parent e657a9e commit c352213

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

src/service-worker.ts

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
import { createHandlerBoundToURL, precacheAndRoute } from 'workbox-precaching'
2-
import { NavigationRoute, registerRoute } from 'workbox-routing'
1+
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching'
2+
import { NavigationRoute, registerRoute, Route } from 'workbox-routing'
3+
import * as navigationPreload from 'workbox-navigation-preload'
4+
import { NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies'
35
import { clientsClaim } from 'workbox-core'
46

57
declare let self: ServiceWorkerGlobalScope
@@ -11,10 +13,40 @@ self.addEventListener('message', (event) => {
1113
}
1214
})
1315

14-
// self.__WB_MANIFEST is default injection point
16+
clientsClaim()
17+
18+
// Precache the manifest
1519
precacheAndRoute(self.__WB_MANIFEST)
1620

17-
// to allow work offline
18-
registerRoute(new NavigationRoute(createHandlerBoundToURL('index.html')))
21+
// clean old assets
22+
cleanupOutdatedCaches()
1923

20-
clientsClaim()
24+
// Enable navigation preload
25+
navigationPreload.enable()
26+
27+
// Create a new navigation route that uses the Network-first, falling back to
28+
// cache strategy for navigation requests with its own cache. This route will be
29+
// handled by navigation preload. The NetworkOnly strategy will work as well.
30+
const navigationRoute = new NavigationRoute(
31+
new NetworkFirst({
32+
cacheName: 'navigations',
33+
}),
34+
)
35+
36+
// Register the navigation route
37+
registerRoute(navigationRoute)
38+
39+
// Create a route for image, script, or style requests that use a
40+
// stale-while-revalidate strategy. This route will be unaffected
41+
// by navigation preload.
42+
const staticAssetsRoute = new Route(
43+
({ request }) => {
44+
return ['image', 'script', 'style'].includes(request.destination)
45+
},
46+
new StaleWhileRevalidate({
47+
cacheName: 'static-assets',
48+
}),
49+
)
50+
51+
// Register the route handling static assets
52+
registerRoute(staticAssetsRoute)

0 commit comments

Comments
 (0)