项目作者: sakralbar

项目描述 :
Simple lazy loader with support for img, picture, video, iframe and background images.
高级语言: JavaScript
项目地址: git://github.com/sakralbar/medialazyloader.git
创建时间: 2018-05-24T10:22:53Z
项目社区:https://github.com/sakralbar/medialazyloader

开源协议:

下载


mediaLazyLoader.js (Simple lazy loader)

mediaLazyLoader.js is a small lazy loading script for <img>, <picture>, <video> and <iframe> elements with background images support.

Usage

First, connect the script to your project:

  1. <script src="medialazyloader.js"></script>

Than add a class “lazy” to all the elements that should use lazy loading:

  1. <img class="lazy" src="img/image.jpg">
  2. <picture>
  3. <source srcset="img/image.webp">
  4. <source srcset="img/image.png">
  5. <img class="lazy" src="img/image.png" alt="">
  6. </picture>
  7. <video class="lazy" controls="" preload="none">
  8. <source src="bg.webm" type="video/webm">
  9. </video>
  10. <iframe class="lazy" src="https://www.youtube.com/embed/dfIHfdg?rel=0&showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Now replace all the “src” attributes with the “data-src” and add your placeholder or lowres images to “src” like:

  1. <img class="lazy" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="img/image.jpg">

In this case, I used the image code of the gif format is one pixel in size.

Background images

You can add a class “lazy” to any element that has a background image. After the element appears in the viewport, class “lazy_loaded” is added to class “lazy”. You can use this as follows:

  1. .block{
  2. background-image: url(../img/placeholder.png);
  3. }
  4. .block.lazy_loaded{
  5. background-image: url(../img/full-bg.jpg);
  6. }

When an element is loaded, a “loaded” event fires.