Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save katakumby/e448d2371d253dd9079db69fe1601464 to your computer and use it in GitHub Desktop.
Save katakumby/e448d2371d253dd9079db69fe1601464 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