最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Vuejs cache images from url, avoid re-fetching - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 4

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 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()
);
发布评论

评论列表(0)

  1. 暂无评论