6

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/background@2x.png 2x,
          https://s3-eu-west-1.amazonaws.com/cornerjob-cdn/background@3x.png 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?
Jose Paredes
  • 3,882
  • 3
  • 26
  • 50

2 Answers2

3

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/

simsom
  • 2,446
  • 1
  • 13
  • 13
  • I need to figure it out before the current src-set was loaded, that's why it's lazy loading (base on the device pixel density ), and I rather an own implementation for this. I want to avoid using third party libraries – Jose Paredes Sep 15 '17 at 14:30
0

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

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