Search code examples
vue.jscachingprogressive-web-appsworkboxnuxt.js

Workbox cache not used by <img /> tag


Setup

"workbox-cdn": "^5.1.4",
"nuxt": "^2.15.2"

Context

My app, Pictalk, let users save and get pictograms. So basically every user has a custom set of pictograms. For now, it works only online but I want to implement offline-mode.

Technical Details

I display all my pictograms with the html <img .../> tag. Every time I load a new pictogram I do so:

created(){
          if(navigator.onLine){
          caches.open('pictos').then((cache) => {
            cache.add(this.collection.path)
            .then(() => {})
            .catch((err)=> {console.log(err)})
          });
      }
  },

Here is a screenshot of the Cache Storage : enter image description here As we see the URL is correct and the requests are cached correctly.

Problem

The <img .../> tag doesn't use the workbox cache I created. enter image description here


Solution

  • Found out the solution here and here.

    Here is the files I had to modify in order to make it work :

    First, my <img/> tags had to use the crossorigin="anonymous" method :

    <img class="image" style :src="path" crossorigin="anonymous"/>

    Once the <img/> tags are more flexible with their origin we can start building our custom registered workbox route:

    // plugins/workboxConfig.js
    workbox.routing.registerRoute(
      new RegExp('https://myapi\\.somewhere\\.com/pictalk/image/.*\\.(png|jpg|jpeg)'),
      new workbox.strategies.CacheFirst({
        cacheName: 'pictos',
        plugins: [
          new workbox.cacheableResponse.CacheableResponsePlugin({ statuses: [200] }),
          new workbox.rangeRequests.RangeRequestsPlugin(),
        ],
        matchOptions: {
          ignoreSearch: true,
          ignoreVary: true
        }
      }),
    );
    

    I had to declare this file here in the nuxtjs.config.js :

    pwa: {
       workbox: {
          cachingExtensions: '@/plugins/workboxConfig.js'
       }
    }