How to implement service workers in an AngularJS application for offline use

I am trying to implement a service worker in one of my AngularJS applications. Based on the tutorials (mostly MDN ), I came up with the following implementation to combine it with AngularJS.

Firstly, since app.run() seems to be the right place. My run block has the following code:

 if ('serviceWorker' in navigator) { navigator.serviceWorker.register('workerFile.js') .then(function(reg) { console.log('Registration done'); },function(error) { console.log('Registration failed with ' + error); }); } 

My working service files are similar:

 this.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.addAll([ 'index.html' ]); }) ); }); 

and

 this.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) ); }); 

Having done this, I expect the index.html file to be cached and maintained offline. But this is not so. In online mode, the file is serviced every time for the server (displayed in the violin).

I tried changing this to self in a working file. It did not help. I am also testing it currently on localhost , so I believe that it should not have security issues. I am very new to the Workers concept in JavaScript, so there are not enough options for testing.

Can someone point me to my mistake here. There are apparently no articles on the Internet on the Internet.

PS: I visited this Question: not very much.

Update:. Once again looking at the documents, I believe that it has something to do with the scope property during registration. How should I define this property to include my entire application. I tried using {scope: '/'} and it does not work.

+5
source share

Source: https://habr.com/ru/post/1268586/


All Articles