📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials jQuery in Practice Lazy Loading Images

Lazy Loading Images

5 min read
Lazy load images by storing the URL in data-src and swapping to src when the image enters the viewport. The native loading='lazy' attribute is simpler and works without JavaScript in all modern browsers.

Lazy Loading with jQuery

$(window).on('scroll', function() {
  $('img[data-src]').each(function() {
    const rect = this.getBoundingClientRect();
    if (rect.top < window.innerHeight) {
      $(this).attr('src', $(this).data('src'))
             .removeAttr('data-src');
    }
  });
}).trigger('scroll');

// HTML
// <img data-src="photo.jpg" src="placeholder.jpg">