Skip to content

Instantly share code, notes, and snippets.

@alexwilson
Created January 2, 2017 03:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexwilson/5dd6de88781b3fdf40aeeb0655b3e92b to your computer and use it in GitHub Desktop.
Save alexwilson/5dd6de88781b3fdf40aeeb0655b3e92b to your computer and use it in GitHub Desktop.
const SITEMAP_CACHE_KEY = 'sitemap-cached-pages-v1'
self.addEventListener('install', event => {
event.waitUntil(cacheSitemap())
})
const cacheSitemap = _ => caches.open(SITEMAP_CACHE_KEY)
.then(cache =>
cacheSitemap()
.then(urls => urls.map(u => u.toString()))
.then(urls => cache.addAll(urls))
)
const fetchSitemap = _ => new Promise((resolve, reject) => {
fetch('./sitemap.xml')
.then(res => res.text())
.then(sitemap => resolve(extractUrlsFromSitemap(sitemap)))
.catch(reject)
})
const extractUrlsFromSitemap = sitemap => {
const parser = new DOMParser().parseFromString(sitemap, "text/xml")
return Array.prototype.slice.call(parser.querySelectorAll('url>loc'))
.map(loc => new URL(loc.textContent))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment