javascriptservice-workerbrowser-cachebase-urlcacheapi

How to load website offline from base url using Service Workers and Cache Api?


When you visit this web site https://bugs.stringmanolo.ga/index.html, while navigating around the main.js file is calling a method from ff.js file to cache a good amount of the resources. So next time you land to the web the files are directly taken from your browser cache without make any request.

This means if you visited my website before, you can load it again without internet conection.

The problem is, this only works if you directly time the index.html file in the addressbar. Lame.

Thid url dosn't work loaded offline. https://bugs.stringmanolo.ga

This other one works fine. https://bugs.stringmanolo.ga/index.html

How can i make the web cache also loads the index.html when the base url is requested?


Solution

  • In your cache array list add a root entry. That's it.

    var CACHELIST = [
        "/",
        // rest of resource list
    ];
    
    self.addEventListener("install", function (event) {
        console.log("Installing the Service Worker!");
        caches.open(CACHENAME)
            .then(cache => {
                cache.addAll(CACHELIST);
            });
    });