I'm building a simple gallery + slideshow app.
In the gallery ponent I have all the urls and display them in a GalleryItem
ponent.
<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 ponent.
<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?
I'm building a simple gallery + slideshow app.
In the gallery ponent I have all the urls and display them in a GalleryItem
ponent.
<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 ponent.
<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?
Share Improve this question asked May 15, 2019 at 9:40 TommyFTommyF 7,1608 gold badges38 silver badges62 bronze badges 3-
14
Turns out the browser does cache, unless the dev-tools are open and
disable-cache
is active, so no issue in production. – TommyF Commented May 16, 2019 at 9:27 - 1 I owe you... spent ages trying to work this out, but I too had 'disable cache' active, oops! – Jake Taylor Commented Aug 13, 2019 at 14:21
- You can try loading all images once and then use v-show to conditionaly display them. This way you will avoid refetching. – Андрей Русев Commented Sep 1, 2020 at 7:16
1 Answer
Reset to default 4You 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 remend 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()
);