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:
1) To see which image the browser is loading, reference here: Is it possible to see which srcset image a browser is using with browser developer tools
2) You will need the custom attribute for any image which comes from the server or static HTML, when lazy loading you could set the property in the function after detecting if the user is HiDPI, see here: https://coderwall.com/p/q2z2uw/detect-hidpi-retina-displays-in-javascript
3) Personally I would use a library like bLazy: https://github.com/dinbror/blazy/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With