-
Notifications
You must be signed in to change notification settings - Fork 1
/
gatsby-browser.js
42 lines (35 loc) · 1.15 KB
/
gatsby-browser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
exports.registerServiceWorker = () => true
let swNotInstalled = true
const prefetchedPathnames = []
exports.onPrefetchPathname = ({ pathname }) => {
// if SW is not installed, we need to record any prefetches
// that happen so we can then add them to SW cache once installed
if (swNotInstalled && `serviceWorker` in navigator) {
prefetchedPathnames.push(pathname)
}
}
exports.onServiceWorkerInstalled = ({ getResourceURLsForPathname }) => {
// stop recording prefetch events
swNotInstalled = false
// grab nodes from head of document
const nodes = document.querySelectorAll(`
head > script[src],
head > link[as=script],
head > link[rel=stylesheet],
head > style[data-href]
`)
// get all resource URLs
const resources = [].slice
.call(nodes)
.map(node => node.src || node.href || node.getAttribute(`data-href`))
for (const resource of resources) {
fetch(resource)
}
// Loop over all resources and fetch the page component and JSON
// to add it to the sw cache.
prefetchedPathnames.forEach(path => {
const { jsUrl, dataUrl } = getResourceURLsForPathname(path)
fetch(jsUrl)
fetch(dataUrl)
})
}