Lazy Load Images Without Javascript

Sustainability of websites is mostly determined by how much electricity the website consumes. All websites consume electricity 24/7. There's a server powered up, listening for requests. They consume it by proxy transferring bits to the client and they consume it on the visitor's computer by rendering the content.

You can't do much about electricity consumption of a server being online 24/7 beyond simplifying your hosting infrastructure (you don't need a load balancer). What's easier to control is the the number of bits you send to clients who visit your website.

Images are a large source of unnecessary bits. We shouldn't be uploading raw uncompressed 40MB images designed for a poster to display on a smart phone. They'll load slow, chew through our visitor's data plan, and consume unnecessary electricity to transfer and render such a large image. You should resize your images for the web.

Traditionally images are input into a website with a simple image tag like below:

<img src="https://jamesvandyne.com/wp-content/uploads/2020/10/voted.png" alt="Ballot approved" border="0" width="600" >

You tell the browser where the image is, give it some alt text for cases where the image doesn't display / accessibility purposes, and maybe even set a size. Once your browser encounters this tag it will dutifully download and display the image. Life is good.

But what if that image is halfway down the page and completely off screen? Doesn't matter - still downloaded.
It doesn't matter that they may not scroll down far enough to see the image, it's in your markup the browser downloads it. This is a waste of electricity and bandwidth.

There are methods using Javascript to dynamically change the src attributes of your image tags when the user scrolls near, but then your simple image tag now requires Javascript and client side computation just to display. It's not an elegant solution.

Turns out there's a better way without Javascript using the loading attribute on your images. Support is in all major browsers since mid 2019 / early 2020. It works out of the box on Firefox/Chrome, but it must must be enabled in Safari under the Advanced > Experimental Features settings for now.

Graph displaying caniuse data for the loading attribute

By simply adding loading="lazy" to our image tags the browser will lazy load our images, i.e. it won't download the image until is nearly in view.

So by modifying the example above to

<img src="https://jamesvandyne.com/wp-content/uploads/2020/10/voted.png" alt="Ballot approved" border="0" width="600" loading="lazy">

we can reduce the number of data transfers, reduce total transfer size (unless they scroll the image into view), reduce electricity consumption across the board, and improve page load times. It's a win-win-win.