6
votes

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?
2
Try this jQuery plugin :jQuery LazyAnimay
@Animay I would like an own solution, I'm not even using jqueryJose Paredes

2 Answers

3
votes

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/

0
votes

This might help you checkout a very nice lazy loading plugin Compatible with All Browsers and IE7+.

http://luis-almeida.github.io/unveil/