Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Exploration of how a service worker's fetch handler affects the DevTools Network panel
<html>
<head>
<title>DevTools Test</title>
</head>
<body>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js');
// Wait until the SW has taken control of the page before inserting the <script> elements.
// That way we can be sure the SW's fetch handler will intercept them.
navigator.serviceWorker.ready.then(() => {
['one.js', 'two.js', 'three.js'].forEach(url => {
var scriptElement = document.createElement('script');
scriptElement.src = url;
document.body.appendChild(scriptElement);
});
});
}
</script>
<p>Nothing to see here! Check the DevTools Network panel.</p>
</body>
</html>
// I'm requested from the network inside the SW's fetch handler.
self.addEventListener('install', event => {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', event => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
if (event.request.url.endsWith('one.js')) {
// Requests for one.js will result in the SW firing off a fetch() request,
// which will be reflected in the DevTools Network panel.
event.respondWith(fetch(event.request));
} else if (event.request.url.endsWith('two.js')) {
// Requests for two.js will result in the SW constructing a new Response object,
// so there won't be an additional network request in the DevTools Network panel.
event.respondWith(new Response('// no-op'));
}
// Requests for anything else won't trigger event.respondWith(), so there won't be
// any SW interaction reflected in the DevTools Network panel.
});
// The SW's fetch handler ignores me, so I'm just requested from the page.
// I'm never actually requested.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.