dinbror / blazy

Hey, be lazy! bLazy.JS is a lightweight pure JavaScript script for lazy loading and multi-serving images. It's working in all modern browsers including IE7+.
http://dinbror.dk/blazy
MIT License
2.63k stars 356 forks source link

Added lazy loading support on wrapper elements #135

Open tkosse opened 7 years ago

tkosse commented 7 years ago

solves #65 and also somehow solves #103

Now you can do the following:

<div class="b-lazy">
  <img data-src="test.jpg">
  ...
  <video>
    <source data-src="video.mp4" type="video/mp4">
    <source data-src="video.ogv" type="video/ogv">
  </video>
  ...
  <iframe data-src="some_page.html"></iframe>
</div>

All lazy loadable elements in the div get loaded automatically all at once when the div appears in the viewport. When all elements have been loaded a specified success or error function will only be executed once. I tried to implement it as general as possible by keeping the actual behaviour.

I couldn't find any library that would support this so it seems to be pretty unique but however really powerful. I need this behaviour i. e. for libraries like BalancedGallery where the images get arranged in a nice way after they have been loaded. Complex example:

<div class="b-lazy horizontal-gallery">
  <img data-src="1.jpg">
  ...
  <img data-src="20.jpg">
</div>
<div class="b-lazy horizontal-gallery">
  <img data-src="21.jpg">
  ...
  <img data-src="40.jpg">
</div>
...

<script type="text/javascript">
  var bLazy = new Blazy({loadInvisible: true, success: function(element, allElementsSucceeded){
    if(!allElementsSucceeded){ // some elements failed to load
      var errorElements = document.getElementsByClassName('b-error');
      var i = 0;
      while(i < errorElements.length) {
        errorElements[i].parentNode.removeChild(errorElements[i]);
      }
    }
    if(element.className.includes('horizontal-gallery')) { 
      $(element).BalancedGallery();
    }
  }});
</script>

Every time a div scrolls in the viewport all images inside get loaded and after that they get displayed in a nice way. This creates an "endless" scrolling effect on the gallery without loading all images on page load.

If PR is accepted I could also update the documentation.

If there are any questions feel free to ask me.