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?
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()
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With