Prevent ServiceWorker from caching content found on outside domains

26 Views Asked by At

I'd like to prevent some external domain requests from being saved/cached.

For example, if my domain is abc.com I want to use a serviceworker to cache all the .js, .css, and .png files requests to help improve its overall speed. I also want to cache all the non-local files I use found on CDNs. But some resources I don't want to cache because I need them to help me track my traffic like googletagmanager.com, connect.facebook.net, and s.pinimg.com. This third type of file must always be pulled directly to help keep my site traffic data as accurate as possible. Herein lays my problem...

I use the code below to make sure I don't cache local files like my 'dynamically generated' language-specific payment pages or my admin templates. But I don't know how to exclude specific domains.

if(!/(\/(([a-z]{2,3})(-[a-z]{2,3})?)\/payment\/(.*))|(\/(([a-z]{2,3})(-[a-z]{2,3})?)\/admin\/)/i.test(event.request.url)){

    /* Bunch of fetch code goes here to do the normal stuff... */

} else {
    
    /* This side of the else statement calls the 'dynamically generated' language-specific payment pages and my admin templates from the server but does not cache them. It just keeps it fresh and always coming from the source. */

    event.respondWith(fetch(event.request, {mode:'no-cors'}));
}

So the question is, is there a way to specify just the domain name in my test? Something like this: i.test(event.request.domain)

I've tried searching for the above code but can't find it or an example of how to do this. At the very least, I don't know how to search Google for something I don't know how to ask for...

Thanks for any insights you guys have,

Vince

0

There are 0 best solutions below