What's the right way to implement offline fallback with workbox












1















I am implementing PWA into my project, I have setted up the serviceworker.js, and I am using workbox.js for cache routing and strategies.



1- I add the offline page to cache on install event, when a user first visit the site:



/**
* Add on install
*/
self.addEventListener('install', (event) => {
const urls = ['/offline/'];
const cacheName = workbox.core.cacheNames.runtime;
event.waitUntil(caches.open(cacheName).then((cache) => cache.addAll(urls)))
});


2- Catch & cache pages with a specific regex, like these:



https://website.com/posts/the-first-post



https://website.com/posts/



https://website.com/articles/



workbox.routing.registerRoute(
new RegExp('/posts|/articles'),
workbox.strategies.staleWhileRevalidate({
cacheName: 'pages-cache'
})
);


3- Catch errors and display the offline page, when there's no internet connection.



/**
* Handling Offline Page fallback
*/
this.addEventListener('fetch', event => {
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request.url).catch(error => {
// Return the offline page
return caches.match('/offline/');
})
);
}
else{
// Respond with everything else if we can
event.respondWith(caches.match(event.request)
.then(function (response) {
return response || fetch(event.request);
})
);
}
});


Now this is working for me so far if I visit for example: https://website.com/contact-us/ but if I visit any url within the scope I defined earlier for "pages-cache" like https://website.com/articles/231/ this would not return the /offline page since it's not in the user cache, and I would get a regular browser error.



There's an issue in how errors are handled, when there's a specific caching route by workbox.



Is this the best method to apply for offline fallback? how can I catch errors from these paths: '/articles' & '/posts' and display an offline page?




Please refer as well to this answer where there's a different
approach to applying the fallack with workbox, I tried it as well same
results. Not sure which is the accurate approach for this.











share|improve this question





























    1















    I am implementing PWA into my project, I have setted up the serviceworker.js, and I am using workbox.js for cache routing and strategies.



    1- I add the offline page to cache on install event, when a user first visit the site:



    /**
    * Add on install
    */
    self.addEventListener('install', (event) => {
    const urls = ['/offline/'];
    const cacheName = workbox.core.cacheNames.runtime;
    event.waitUntil(caches.open(cacheName).then((cache) => cache.addAll(urls)))
    });


    2- Catch & cache pages with a specific regex, like these:



    https://website.com/posts/the-first-post



    https://website.com/posts/



    https://website.com/articles/



    workbox.routing.registerRoute(
    new RegExp('/posts|/articles'),
    workbox.strategies.staleWhileRevalidate({
    cacheName: 'pages-cache'
    })
    );


    3- Catch errors and display the offline page, when there's no internet connection.



    /**
    * Handling Offline Page fallback
    */
    this.addEventListener('fetch', event => {
    if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
    event.respondWith(
    fetch(event.request.url).catch(error => {
    // Return the offline page
    return caches.match('/offline/');
    })
    );
    }
    else{
    // Respond with everything else if we can
    event.respondWith(caches.match(event.request)
    .then(function (response) {
    return response || fetch(event.request);
    })
    );
    }
    });


    Now this is working for me so far if I visit for example: https://website.com/contact-us/ but if I visit any url within the scope I defined earlier for "pages-cache" like https://website.com/articles/231/ this would not return the /offline page since it's not in the user cache, and I would get a regular browser error.



    There's an issue in how errors are handled, when there's a specific caching route by workbox.



    Is this the best method to apply for offline fallback? how can I catch errors from these paths: '/articles' & '/posts' and display an offline page?




    Please refer as well to this answer where there's a different
    approach to applying the fallack with workbox, I tried it as well same
    results. Not sure which is the accurate approach for this.











    share|improve this question



























      1












      1








      1


      1






      I am implementing PWA into my project, I have setted up the serviceworker.js, and I am using workbox.js for cache routing and strategies.



      1- I add the offline page to cache on install event, when a user first visit the site:



      /**
      * Add on install
      */
      self.addEventListener('install', (event) => {
      const urls = ['/offline/'];
      const cacheName = workbox.core.cacheNames.runtime;
      event.waitUntil(caches.open(cacheName).then((cache) => cache.addAll(urls)))
      });


      2- Catch & cache pages with a specific regex, like these:



      https://website.com/posts/the-first-post



      https://website.com/posts/



      https://website.com/articles/



      workbox.routing.registerRoute(
      new RegExp('/posts|/articles'),
      workbox.strategies.staleWhileRevalidate({
      cacheName: 'pages-cache'
      })
      );


      3- Catch errors and display the offline page, when there's no internet connection.



      /**
      * Handling Offline Page fallback
      */
      this.addEventListener('fetch', event => {
      if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
      event.respondWith(
      fetch(event.request.url).catch(error => {
      // Return the offline page
      return caches.match('/offline/');
      })
      );
      }
      else{
      // Respond with everything else if we can
      event.respondWith(caches.match(event.request)
      .then(function (response) {
      return response || fetch(event.request);
      })
      );
      }
      });


      Now this is working for me so far if I visit for example: https://website.com/contact-us/ but if I visit any url within the scope I defined earlier for "pages-cache" like https://website.com/articles/231/ this would not return the /offline page since it's not in the user cache, and I would get a regular browser error.



      There's an issue in how errors are handled, when there's a specific caching route by workbox.



      Is this the best method to apply for offline fallback? how can I catch errors from these paths: '/articles' & '/posts' and display an offline page?




      Please refer as well to this answer where there's a different
      approach to applying the fallack with workbox, I tried it as well same
      results. Not sure which is the accurate approach for this.











      share|improve this question
















      I am implementing PWA into my project, I have setted up the serviceworker.js, and I am using workbox.js for cache routing and strategies.



      1- I add the offline page to cache on install event, when a user first visit the site:



      /**
      * Add on install
      */
      self.addEventListener('install', (event) => {
      const urls = ['/offline/'];
      const cacheName = workbox.core.cacheNames.runtime;
      event.waitUntil(caches.open(cacheName).then((cache) => cache.addAll(urls)))
      });


      2- Catch & cache pages with a specific regex, like these:



      https://website.com/posts/the-first-post



      https://website.com/posts/



      https://website.com/articles/



      workbox.routing.registerRoute(
      new RegExp('/posts|/articles'),
      workbox.strategies.staleWhileRevalidate({
      cacheName: 'pages-cache'
      })
      );


      3- Catch errors and display the offline page, when there's no internet connection.



      /**
      * Handling Offline Page fallback
      */
      this.addEventListener('fetch', event => {
      if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
      event.respondWith(
      fetch(event.request.url).catch(error => {
      // Return the offline page
      return caches.match('/offline/');
      })
      );
      }
      else{
      // Respond with everything else if we can
      event.respondWith(caches.match(event.request)
      .then(function (response) {
      return response || fetch(event.request);
      })
      );
      }
      });


      Now this is working for me so far if I visit for example: https://website.com/contact-us/ but if I visit any url within the scope I defined earlier for "pages-cache" like https://website.com/articles/231/ this would not return the /offline page since it's not in the user cache, and I would get a regular browser error.



      There's an issue in how errors are handled, when there's a specific caching route by workbox.



      Is this the best method to apply for offline fallback? how can I catch errors from these paths: '/articles' & '/posts' and display an offline page?




      Please refer as well to this answer where there's a different
      approach to applying the fallack with workbox, I tried it as well same
      results. Not sure which is the accurate approach for this.








      service-worker progressive-web-apps workbox






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 3 '18 at 15:32







      Kash

















      asked Nov 27 '18 at 16:12









      KashKash

      115210




      115210
























          1 Answer
          1






          active

          oldest

          votes


















          1














          I found a way to do it right with workbox.
          For each route I would add a fallback method like this:



          const offlinePage = '/offline/';
          /**
          * Pages to cache
          */
          workbox.routing.registerRoute(//posts.|/articles/,
          async ({event}) => {
          try {
          return await workbox.strategies.staleWhileRevalidate({
          cacheName: 'cache-pages'
          }).handle({event});
          } catch (error) {
          return caches.match(offlinePage);
          }
          }
          );


          In case of using network first strategy this is the method:



          /**
          * Pages to cache (networkFirst)
          */
          var networkFirst = workbox.strategies.networkFirst({
          cacheName: 'cache-pages'
          });

          const customHandler = async (args) => {
          try {
          const response = await networkFirst.handle(args);
          return response || await caches.match(offlinePage);
          } catch (error) {
          return await caches.match(offlinePage);
          }
          };

          workbox.routing.registerRoute(
          //posts.|/articles/,
          customHandler
          );


          More details at workbox documentation here: Provide a fallback response to a route






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53503761%2fwhats-the-right-way-to-implement-offline-fallback-with-workbox%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            I found a way to do it right with workbox.
            For each route I would add a fallback method like this:



            const offlinePage = '/offline/';
            /**
            * Pages to cache
            */
            workbox.routing.registerRoute(//posts.|/articles/,
            async ({event}) => {
            try {
            return await workbox.strategies.staleWhileRevalidate({
            cacheName: 'cache-pages'
            }).handle({event});
            } catch (error) {
            return caches.match(offlinePage);
            }
            }
            );


            In case of using network first strategy this is the method:



            /**
            * Pages to cache (networkFirst)
            */
            var networkFirst = workbox.strategies.networkFirst({
            cacheName: 'cache-pages'
            });

            const customHandler = async (args) => {
            try {
            const response = await networkFirst.handle(args);
            return response || await caches.match(offlinePage);
            } catch (error) {
            return await caches.match(offlinePage);
            }
            };

            workbox.routing.registerRoute(
            //posts.|/articles/,
            customHandler
            );


            More details at workbox documentation here: Provide a fallback response to a route






            share|improve this answer




























              1














              I found a way to do it right with workbox.
              For each route I would add a fallback method like this:



              const offlinePage = '/offline/';
              /**
              * Pages to cache
              */
              workbox.routing.registerRoute(//posts.|/articles/,
              async ({event}) => {
              try {
              return await workbox.strategies.staleWhileRevalidate({
              cacheName: 'cache-pages'
              }).handle({event});
              } catch (error) {
              return caches.match(offlinePage);
              }
              }
              );


              In case of using network first strategy this is the method:



              /**
              * Pages to cache (networkFirst)
              */
              var networkFirst = workbox.strategies.networkFirst({
              cacheName: 'cache-pages'
              });

              const customHandler = async (args) => {
              try {
              const response = await networkFirst.handle(args);
              return response || await caches.match(offlinePage);
              } catch (error) {
              return await caches.match(offlinePage);
              }
              };

              workbox.routing.registerRoute(
              //posts.|/articles/,
              customHandler
              );


              More details at workbox documentation here: Provide a fallback response to a route






              share|improve this answer


























                1












                1








                1







                I found a way to do it right with workbox.
                For each route I would add a fallback method like this:



                const offlinePage = '/offline/';
                /**
                * Pages to cache
                */
                workbox.routing.registerRoute(//posts.|/articles/,
                async ({event}) => {
                try {
                return await workbox.strategies.staleWhileRevalidate({
                cacheName: 'cache-pages'
                }).handle({event});
                } catch (error) {
                return caches.match(offlinePage);
                }
                }
                );


                In case of using network first strategy this is the method:



                /**
                * Pages to cache (networkFirst)
                */
                var networkFirst = workbox.strategies.networkFirst({
                cacheName: 'cache-pages'
                });

                const customHandler = async (args) => {
                try {
                const response = await networkFirst.handle(args);
                return response || await caches.match(offlinePage);
                } catch (error) {
                return await caches.match(offlinePage);
                }
                };

                workbox.routing.registerRoute(
                //posts.|/articles/,
                customHandler
                );


                More details at workbox documentation here: Provide a fallback response to a route






                share|improve this answer













                I found a way to do it right with workbox.
                For each route I would add a fallback method like this:



                const offlinePage = '/offline/';
                /**
                * Pages to cache
                */
                workbox.routing.registerRoute(//posts.|/articles/,
                async ({event}) => {
                try {
                return await workbox.strategies.staleWhileRevalidate({
                cacheName: 'cache-pages'
                }).handle({event});
                } catch (error) {
                return caches.match(offlinePage);
                }
                }
                );


                In case of using network first strategy this is the method:



                /**
                * Pages to cache (networkFirst)
                */
                var networkFirst = workbox.strategies.networkFirst({
                cacheName: 'cache-pages'
                });

                const customHandler = async (args) => {
                try {
                const response = await networkFirst.handle(args);
                return response || await caches.match(offlinePage);
                } catch (error) {
                return await caches.match(offlinePage);
                }
                };

                workbox.routing.registerRoute(
                //posts.|/articles/,
                customHandler
                );


                More details at workbox documentation here: Provide a fallback response to a route







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 3 '18 at 15:42









                KashKash

                115210




                115210
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53503761%2fwhats-the-right-way-to-implement-offline-fallback-with-workbox%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Lallio

                    Unable to find Lightning Node

                    Futebolista