Skip to content

Commit

Permalink
fix(gatsby-plugin-offline): skip prefetching all resources (#16691)
Browse files Browse the repository at this point in the history

Co-authored-by: GatsbyJS Bot <[email protected]>
Co-authored-by: Ward Peeters <[email protected]>
  • Loading branch information
3 people committed Sep 24, 2019
1 parent 34eae00 commit e688b0c
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const { onServiceWorkerActive } = require(`../gatsby-browser`)

it(`does not add prefetch for preconnect/prefetch/prerender`, () => {
const addHeadElement = (tagName, attributes) => {
const el = document.createElement(tagName)
for (let key in attributes) {
el.setAttribute(key, attributes[key])
}
document.head.appendChild(el)
return el
}

// Should not be prefetched
addHeadElement(`link`, { rel: `preconnect`, href: `https://gatsbyjs.org` })
addHeadElement(`link`, { rel: `prefetch`, href: `https://gatsbyjs.org` })
addHeadElement(`link`, { rel: `prerender`, href: `https://gatsbyjs.org` })
addHeadElement(`script`, { src: `https://gats.by/script.js` })
addHeadElement(`style`, { "data-href": `https://gats.by/lazy.css` })
addHeadElement(`link`, {
rel: `stylesheet`,
href: `https://gats.by/style.css`,
})
addHeadElement(`link`, {
rel: `preconnect dns-prefetch`,
href: `https://www.google-analytics.com`,
})

onServiceWorkerActive({
getResourceURLsForPathname: () => [],
serviceWorker: { active: {} },
})

// First five link elements should be the actual resources added above
// The remaining link elements should be the one added by gatsby-browser as prefetch
const links = [].slice.call(document.querySelectorAll(`head > link`))

// Should add prefetch for stylesheets, scripts and lazy-loaded styles
expect(links[5].href).toBe(`https://gats.by/script.js`)
expect(links[5].rel).toBe(`prefetch`)
expect(links[6].href).toBe(`https://gats.by/lazy.css`)
expect(links[6].rel).toBe(`prefetch`)
expect(links[7].href).toBe(`https://gats.by/style.css`)
expect(links[7].rel).toBe(`prefetch`)
})
8 changes: 8 additions & 0 deletions packages/gatsby-plugin-offline/src/gatsby-browser.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
exports.registerServiceWorker = () => true

// only cache relevant resources for this page
const whiteListLinkRels = /^(stylesheet|preload)$/
const prefetchedPathnames = []

exports.onServiceWorkerActive = ({
Expand All @@ -23,6 +25,12 @@ exports.onServiceWorkerActive = ({
// get all resource URLs
const headerResources = [].slice
.call(nodes)
// don't include preconnect/prefetch/prerender resources
.filter(
node =>
node.tagName !== `LINK` ||
whiteListLinkRels.test(node.getAttribute(`rel`))
)
.map(node => node.src || node.href || node.getAttribute(`data-href`))

// Loop over prefetched pages and add their resources to an array,
Expand Down

0 comments on commit e688b0c

Please sign in to comment.