If you want your application works offline or Lie-wifi. You need to use the cache.
Api:
Create Caches:
Caches.open (' Cache_name '). Then ((cache) = { // create name if not exists yet, return cache I F there is aone})
Create Single cache:
Cache.put (request, response); Cache.addall ([ '/foo ', '/bar '])
Get the cache:
Cache.match (Request) Caches.match (Request)
When to start cache:
We can do the cache in ' installing ' service workers, what it would do are fetch everything we need from network and create cache For each of them.
Self.addeventlistener (' Install ',function(event) {varUrlstocache = [ ‘/‘, ' Js/main.js ', ' Css/main.css ', ' Imgs/icon.png ', ' Https://fonts.gstatic.com/s/roboto/v15/2UX7WLTfW3W8TclTUvlFyQ.woff ', ' Https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOD8E0i7KZn-EPnyo3HZu7kw.woff ' ]; Event.waituntil (//Todo:open A cache named ' Wittr-static-v1 ' //ADD cache The URLs from UrlstocacheCaches.open (' Wittr-static-v1 '). Then (cache)={Cache.addall (Urlstocache)}).Catch() ={console.error ("Cannot cache anything"); }) );});
Now we had the create the cache, but it was not a useful until we use the cache.
To use the cache, we can do:
Self.addeventlistener (' Install ',function(event) {varUrlstocache = [ ‘/‘, ' Js/main.js ', ' Css/main.css ', ' Imgs/icon.png ', ' Https://fonts.gstatic.com/s/roboto/v15/2UX7WLTfW3W8TclTUvlFyQ.woff ', ' Https://fonts.gstatic.com/s/roboto/v15/d-6IYplOFocCacKzxwXSOD8E0i7KZn-EPnyo3HZu7kw.woff ' ]; Event.waituntil (//Todo:open A cache named ' Wittr-static-v1 ' //ADD cache The URLs from UrlstocacheCaches.open (' Wittr-static-v4 '). Then (cache)={Cache.addall (Urlstocache)}).Catch() ={console.error ("Cannot cache anything"); }) );}); Self.addeventlistener (' Fetch ',function(event) {Event.respondwith (Caches.match (event.request). Then (response)={ if(response) {returnresponse; }Else{ returnfetch (event.request); } }) )});
So we use ' caches.match ' to get all the caches for request.
In the then block, cache is successfully fetched, we check whether there are cache data, if it is and then return the response ;
If There is no cache data and then we fetch the data from Real-server.
Approach has some problem:
After we go offline mode, the pictures was not showing, this is because we have the cache when the Servcie worker is installed .
So are some problem we need to solve:
[PWA] 7. First Cache when installed