Ignore ajax requests at maintenance staff

I have an application with a basic shell of HTML, CSS and JS. The main content of the page is loaded through several ajax calls to the API, which is located at a different URL to which my application is working. I installed a service worker to cache the main "shell" of the application:

var urlsToCache = [ '/', 'styles/main.css', 'scripts/app.js', 'scripts/apiService.js', 'third_party/handlebars.min.js', 'third_party/handlebars-intl.min.js' ]; 

and respond with the requested cached version. The problem I am facing is that the response of my ajax calls is also cached. I am sure that I need to add code to the fetch event of the work service, which always gets them from the network, rather than looking in the cache.

Here is my fetch event:

 self.addEventListener('fetch', function (event) { // ignore anything other than GET requests var request = event.request; if (request.method !== 'GET') { event.respondWith(fetch(request)); return; } // handle other requests event.respondWith( caches.open(CACHE_NAME).then(function (cache) { return cache.match(event.request).then(function (response) { return response || fetch(event.request).then(function (response) { cache.put(event.request, response.clone()); return response; }); }); }) ); }); 

I am not sure how to ignore API requests. I tried to do this:

 if (request.url.indexOf(myAPIUrl !== -1) { event.respondWith(fetch(request)); return; } 

but according to the network tab in Chrome Dev Tools, all of these answers still come from a service employee.

+6
source share
1 answer

You do not need to use event.respondWith(fetch(request)) to handle requests that you want to ignore. If you return without calling event.respondWith , the browser will select the resource for you.

You can do something like:

 if (request.methd !== 'GET') { return; } if (request.url.indexOf(myAPIUrl) !== -1) { return; } \\ handle all other requests event.respondWith(/* return promise here */); 

IOW, while you can synchronously determine that you do not want to process the request, which you can simply return from the handler, and allow the processing of the request by default. Check out this example.

+9
source

All Articles