I have this basic lazy loading script with retina image @2x and @3x.
(function(doc) {
var div = doc.querySelector('div');
var img = doc.querySelector('img[data-src]');
img.onload = function() {
img.removeAttribute('data-src');
div.classList.add('done');
};
img.setAttribute('src', img.getAttribute('data-src'));
})(document);
img {
width: 300px;
margin: 0 auto;
display: block;
}
img {
opacity: 1;
transition: opacity 0.3s;
}
img[data-src] {
opacity: 0;
}
div {
position: relative;
min-height: 222px;
}
div:after {
content: '';
position: absolute;
width: 50px;
height: 50px;
border-radius: 50%;
border-top: 1px solid #9a9a9a;
border-left: 1px solid #9a9a9a;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -25px;
animation: id 1s linear infinite both;
}
div.done:after {
display: none;
}
@keyframes id {
to { transform: rotateZ(360deg) }
}
<div>
<img
src="https://s3-eu-west-1.amazonaws.com/cornerjob-cdn/background.png"
data-src="https://s3-eu-west-1.amazonaws.com/cornerjob-cdn/background.png"
srcset="https://s3-eu-west-1.amazonaws.com/cornerjob-cdn/[email protected] 2x,
https://s3-eu-west-1.amazonaws.com/cornerjob-cdn/[email protected] 3x">
</div>
The browser determines which image to load depending on the device pixel ratio.
According to this:
- What's the best practice to recognize which image is the browser loading?
- Do I have to set a custom attribute for each retina image I have?
- In general what will be the best approach to solve using lazy loading images with retina images?