JSFiddle - React, Tailwind, and code Playground
by Alexander Tartmin
HTML
<img src="http://lorempixel.com/10/10/sports/1/" data-src='http://lorempixel.com/500/500/sports/1/' alt="">
<img src="http://lorempixel.com/10/10/sports/2/" data-src='http://lorempixel.com/600/600/sports/2/' alt="">
<img src="http://lorempixel.com/10/10/sports/3/" data-src='http://lorempixel.com/1000/1000/sports/3/' alt="">
<div data-src="http://lorempixel.com/1000/1000/animals/1/" style="background-image:url('http://lorempixel.com/20/20/animals/1/')"></div>
<div data-src="http://lorempixel.com/1000/1000/animals/2/" style="background-image:url('http://lorempixel.com/20/20/animals/2/')"></div>
<div data-src="http://lorempixel.com/1000/1000/animals/3/" style="background-image:url('http://lorempixel.com/20/20/animals/3/')"></div>
CSS
img {
width: 200px;
height: 200px;
display: inline-block;
margin-right: 10px;
margin-bottom: 10px;
}
div {
background-size: cover;
width: 200px;
height: 200px;
display: inline-block;
margin-right: 10px;
}
JavaScript
(function(w, d, a) {
w.onload = function() {
a = d.querySelectorAll('*[data-src]');
a.forEach(function(i) {
var n = new Image(),
o = i.dataset.src;
n.onload = function() {
if (i.tagName === 'IMG') {
i.src = o;
} else {
i.style.backgroundImage = 'url("' + o + '")';
}
};
n.src = o;
});
};
})(window, document, []);