Let's talk about loading inline images. They load great on high speed connections but things are changing. More and more users are using 4g mobile or hotspots which means data consumption is a valuable comoddity. Great news! We can use Javascript and HTML together to lazy load images on your web pages. I'll walk you through some javascript tricks to "Lazy" load images.

loading="lazy"

loading="lazy" is a recent standard added to chrome and mozillla. According to Web.dev Chrome and Firefox both support lazy-loading with the loading attribute. This attribute can be added to <img> elements, and also to <iframe> elements. A value of lazy tells the browser to load the image immediately if it is in the viewport, and to fetch other images when the user scrolls near them. This method is great for optimization and doesnt require any javascript. Just pure plain HTML :)

How to lazy load with Javascript

Let's try a javascript solution incase the html solution isn't enough. For our trick we want to load any "visible" images when a user scrolls down the page or resizes the window.

We can use jQuery's .on method and the event handelers scroll and resize to run the function that checks for the images being in the viewport. If the function returns true it will fire and replace the src value of each img element with the value defined in the element's data-src value. This trick will decrease initial page load and optimize the load time on mobile devices.

View Code Example Below:


How to Implement

  • Use when your page has lots of images to load
  • We can do this with a combination of plain JS & jQuery
  • This should be cross browser compatible and work on mobile devices
  • Load JQuery in the head of your document

The "trick" here is to add "data-src" to all of your <img> tags and set the initial src value to a single placeholder image. We'll loop through the elements that have the attribute data-src and use .filter() to check/test if they are within the "viewport". Finally we'll run our function onload and when a user scrolls or resizes our page.


Updated: Jan 2022


Feel free to share this Source Code and use on your personal Website Projects.
All scripts and snippets authored by https://www.andysotura.com