How to Defer Image Loading with Vanilla JavaScript

It’s well-known that loading an HTML page with over 100 images can significantly slow down the initial render if asset loading isn’t managed properly. Think of it like unloading containers from a ship—each image adds to the load time. When a bot, crawler, or user visits such a page, they might experience delays before the content becomes visible. To address this, instead of traditional lazy loading, I’ve found that deferring image loading entirely until after the page has loaded yields better performance.​

Once the page has fully initialized, the images are then loaded automatically. This deferring method resembles lazy loading but ensures that all images render after the main content, improving the user experience. The key is to avoid using loops like forEach() or for to insert images. Instead, we leverage the DOM’s capabilities to handle the insertion efficiently.​

I have a stress test on CodePen loading 999 images in a blink.

The core of this technique involves using an <a> element with a data-defer-src attribute:

<a href="#" data-defer-src="https://picsum.photos/seed/picsum/200/200"></a>

And a snippet of vanilla JavaScript:

window.addEventListener('load', function() {
  const anchors = document.querySelectorAll('a[data-defer-src]');
  anchors.forEach(anchor => {
    const src = anchor.getAttribute('data-defer-src');
    const img = document.createElement('img');
    img.src = src;
    img.width = 200;
    img.height = 200;
    img.alt = '';
    img.className = 'deferred';
    anchor.insertBefore(img, anchor.firstChild);
  });
});

See the Pen JavaScript data-defer-src Test by Ciprian (@ciprian) on CodePen.

on in JavaScript DOM, JavaScript Pagination | Last modified on

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *