Mohannad Hisham
Mohannad Hisham

Reputation: 56

Service Worker - Caching of a static website

I was wondering if this was a good way for caching resources (CSS or Fonts) for a static website.

self.addEventListener("fetch",(e)=>{
    let requestUrl = e.request.url;
    e.respondWith(
        caches.match(e.request).then((res)=>{
            return res || fetch(e.request).then((netres)=>{
                return caches.open(cacheStore).then((cache)=>{
                    cache.put(requestUrl,netres.clone());
                    return netres;
                });
            });
        })
    );
});

Everything on the website is static, just some external links and some functions, frameworks, and fonts to style the website. It first searches the cache for the response and if it didn't find any match, it fetches the request and stores it in the cache for the next time.

Is it better to add the links manually on the install event? Is there any security concerns with this approach?

Upvotes: 0

Views: 158

Answers (1)

oninross
oninross

Reputation: 999

You could follow how Google does a simple prefetch of assets. Here is the link to the service worker file.

Upvotes: 1

Related Questions