Reputation: 21
Service Worker is not getting registered as I'm getting the error "a bad http response code 404 was received when fetching the script". What might be the step that I'm missing? I have registered service worker using:
<script>
if('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/ServiceWorker.js')
.then(function() { console.log("Service Worker Registered"); });
}
</script>
Also, can we cache an .aspx
page in a service worker?
Upvotes: 2
Views: 3485
Reputation: 1
Using nrwl (Nx.js) you need to run nx build your_app. It will create a public folder dist with the mockServiceWorker.js then run : npm run msw dist It will initialize to this folder to download stuff while service your app.
Upvotes: 0
Reputation: 1033
Two things are possible:
Upvotes: 0
Reputation: 483
Check path of your ServiceWorker.js
is accessible in your file to register serviceWorker. Other hand Which file you trying to fetch, that should be inside the scope of service worker.
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/resources/ServiceWorker.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
As above snippet can fetch:
/resources/js/***.js //200 Ok
/resources/css/***.css //200 Ok
/static/***.js //404 Not found, because not in scope
Upvotes: 0
Reputation: 226
This script inside the page is just unable to locate /ServiceWorker.js
and could be due to 1 thing out of 2. Either the file /ServiceWorker.js
does not exist in your root website folder or you mistyped the name. There's no missing step at all and the snippet looks ok.
The other question is yes, you can not only cache static files like fonts, CSS and JS, but also anything dynamic network response.
Inside /ServiceWorker.js
add:
self.addEventListener('fetch', function(event) {
console.log(event.request);
});
That will log in your browser console the URLs you are trying to request and you servers, images, text, etc.. and you can clone any response object and put it in your cache to be served from there on next visit.
Goog example / tutorials: https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker#serving_files_from_the_cache
Upvotes: 2