Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs cache images from url, avoid re-fetching

I'm building a simple gallery + slideshow app.
In the gallery component I have all the urls and display them in a GalleryItem component.

<gallery-item v-for="i in images" :item="i" :key="i.uid"/>

GalleryItem then uses

<img :src="item.url"/>

to display the image.
If the user clicks on any GalleryItem it will be highlighted in a lightbox/slideshow component.

<lightbox :item="highlightedItem"/>

which again uses

<img :src="item.url"/>

I naively expected the browser to cache that request and not reload the exact same url, but that's exactly what's happening.

Is there any elegant way to avoid this and cache the image when loaded once?

like image 359
TommyF Avatar asked Oct 16 '22 15:10

TommyF


1 Answers

You can implement caching images with a service worker.

An example service worker library that you can use is Workbox. With Workbox you can define a URL you want to cache and multiple different caching strategies. Similar to the following code example just replace the RegExp with one that fits your use case, for example using the image extensions.

If your images don't change as in the same url always points to the same image, I would recommend you to use the cacheFirst strategy, as then you will not need to send a request to the server if the image is already in the cache.

workbox.routing.registerRoute(
  new RegExp('/styles/'),
  new workbox.strategies.CacheFirst()
);
like image 87
Lassi Uosukainen Avatar answered Nov 15 '22 05:11

Lassi Uosukainen