Dtrav
Dtrav

Reputation: 417

How can I not lazy load images that were previously cached by the browser?

I have an interesting conundrum that's been bugging me off and on for some time now and can't seem to find out a solution. Currently, I'm using a basic jQuery method (using data-src in an img tag with src placeholder image and using jQuery to convert data-src to src) to lazyload images the user sees right after the page load with a fade in animation. This has obviously greatly increased load times since implemented but at the cost of images that are cached having the initial data-src still on the img tag on page load and switching (and fading) from the placeholder image everytime, for all images.

I'm looking for a solution to only lazyload images that aren't previously cached by the browser. Currently all the lazy loaded images get cached through a CDN and from the network, are immediately loaded in but that src change and animation is still there.

Not looking for new plugins (or responses that say "just remove the animation") just a js way (if possible) to loop through img tags on the page, grab the data-src attribute and move it to the src attribute on page load if the image is already cached in the browser. The last part of which is what I have been hard pressed to find a solution for.

If this is easier done through the back-end, my app is using Ruby on Rails.

Upvotes: 1

Views: 1896

Answers (1)

TKoL
TKoL

Reputation: 13892

You can use the asynchronous "window.caches.match" function like so:

window.caches.match('/assets/css/main.css?v=8d1207d318')
  .then(cache => {
    if (cache) {
        // load image url immediately
    }
  })

Read here: https://www.darrenlester.com/blog/instantly-loading-cached-images

Upvotes: 1

Related Questions