Reputation: 537
I am developing the code for a Service Worker using Cloudflare Workers (JS). I want to fire the Service Worker only for HTML requests, so that I can optimize the number of requests being evaluated. Right now I am using this code:
addEventListener('fetch', async event => {
if (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html')) {
event.respondWith(handleRequest(event.request));
}
});
async function handleRequest(request) {
const response = await fetch(request);
// Clone the response so that it's no longer immutable
const newResponse = new Response(response.body, response);
// Add a custom header with a value
newResponse.headers.append('x-h-w', 'hello world');
return newResponse;
}
While it is only adding the custom header to the request associated with the HTML element, the Service Worker is evaluating every request from the website (styles, images, scripts etc.).
Is there a way to evaluate only HTML requests? (without consuming quota evaluating the other type of requests)
Upvotes: 1
Views: 458
Reputation: 933
This is not possible, I fear. As soon as you add an event listener on the "fetch" event, you'll receive all events. But just not invoking the event.respondWith
is the right thing to do if you are not interested.
Why would you be worried about the "quota"? You should not notice the performance impact or can you really measure any difference?
As a tiny hint: You don't need to check the "accept" header, because only the initial request is usually an HTML request and this request has some special mode:
event.request.mode === 'navigate'
This should be even less performance overhead 🙃
Upvotes: 1