1

I made a car dealership page. I store data about cars in an array of objects, then I loop through it to insert data into my HTML file to display on a page. It works fine.

The problem arises when I try to add a lazy load function using intersection observers. The stuff gets put into page correctly but the intersection observer doesn't see the images and doesn't load them.

Here is a link to a codepen https://codepen.io/russiandobby/pen/xxxJvxv?editors=0010 , if you change data-src to src it will work.

How can I make it work so I can have lazy-loading.

 <img data-src="${car.img}" alt="jag1" class="card-img-top car-img popup-img">
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
  • I provided an answer here: https://stackoverflow.com/questions/52217333/how-to-bind-dynamically-generated-element-to-intersection-observer – electronixG Jun 21 '23 at 16:05

1 Answers1

1

Your main code is fine.

The only issue is that it runs at the wrong time. While you DOM generation code runs on DOMContentLoaded, you try to attach the observer right away, so no images are in the DOM yet.

You will need to put your observer code inside the DOMContentLoaded as well, or create a method and call it from there.

Updated code: https://codepen.io/gpetrioli/pen/XWWBvQm?editors=0010

(your codepen would also fail because you use a jquery plugin without including the jQuery library)

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317