Deferring images without lazy loading or jQuery

HTML • JavaScript

Place this function either in your page header or shared JS file for reference on multiple pages. It will loop through all images that have a "data-src" attribute and use that value to replace the img object's SRC value.

function imgOnloadDefer() {
	var imgDefer = document.getElementsByTagName('img');
	for (var i=0; i<imgDefer.length; i++) {
		if(imgDefer[i].getAttribute('data-src')) {
window.onload = imgOnloadDefer();

Structure your image HTML tag(s) with a blank image URL listed as the src or you can use a base64 image. Place the actual image SRC in the attribute data-src.

<!-- USING A BASE64 image as the default (this example below will be a 1px black dot) -->
<img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="YourImageHere1.jpg" alt="image 1">
<img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" data-src="YourImageHere2.jpg" alt="image 2">

<!-- Using a blank 1px image like spacer.gif  -->
<img src="spacer.gif" data-src="YourImageHere1.jpg" alt="image 1">
<img src="spacer.gif" data-src="YourImageHere2.jpg" alt="image 2">

Written by Patrick Sexton

Posted by fbrefere001 on Thursday August 25, 2016