简体   繁体   中英

Lazy Loading doesn't work for Ajax Request

I have implemented lazy load from David Walsh's tips here (tip 1) https://www.sitepoint.com/five-techniques-lazy-load-images-website-performance/ and it works great on a fresh load of the site. But it doesn't work when the images are filtered and re-rendered with an ajax request. I'm using Rails and the images are contained in a partial which is re-rendered on an ajax request on a click of the filter. When the images are filtered through the ajax request only the blurry placeholder image loads and not the actual image.

My js code is

[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
  img.setAttribute('src', img.getAttribute('data-src'));
  img.onload = function() {
  img.removeAttribute('data-src');
  };
});

My image code is

<%=image_tag(activity.lead_image.xs_thumb, :class => "card-img-top", :alt => "Card image cap", data: { "src" => image_path(activity.lead_image.thumb) }) %>

Any steer will be much appreciated!

Your JavaScript is run one-time at page load, when your ajax request happens you have a new set of img tags which haven't been evaluated.

You likely want to invoke your lazy-loading Javascript again after your ajax call. You could encapsulate your JS within a function, and invoke it after your ajax call has completed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM