The image delayed loading technology is very practical for websites with high traffic. Currently, images are widely used in websites. If they are not processed, they will put great pressure on the server and bandwidth. By only rendering images in the area visible to the current user, you can greatly reduce the number of website requests and reduce network bandwidth resources.
unveil
This is a very lightweight short-time image loading component
It supports modern browsers and IE7+, and there are nearly 3K stars (follows) on Github
Use
General pictures
<img src="bg.png" data-src="img1.jpg" />
For support Retina (retina screen) device
<img src="bg.png" data-src="img2.jpg" data-src-retina="img2-retina.jpg" />
Application
$(document).ready(function() { $("img").unveil(); });
Support callback
$("img").unveil(200, function() { $(this).load(function() { this.style.opacity = 1; }); });
Support manual trigger
$("img").trigger("unveil");
jquery_lazyload
Can delay loading of images of large websites, and then render when scrolling to the area. There are 4K followers on Github.
Use
Reference jQuery and lazyload.js
<script src="jquery.js" type="text/javascript"></script> <script src="jquery.lazyload.js" type="text/javascript"></script>
Images that need to be delayed loaded
<img class="lazy" data-original="img/example.jpg" width="640" height="480">
Apply
$(function() { $("img.lazy").lazyload(); });
echo
An independent logo-type JavaScript image delayed loading library. Does not rely on jQuery, only 2K after compression.
Support IE8+
Use
<body> <img src="img/blank.gif" alt="Photo" data-echo="img/photo.jpg"> <script src="dist/echo.js"></script> <script> echo.init({ offset: 100, throttle: 250, unload: false, callback: function (element, op) { console.log(element, 'has been', op + 'ed') } }); // echo.render(); //手动触发调用 </script> </body>
layzr.js
An Image Lazy Loading component just released a few days ago, which is small, fast and has no dependencies (does not rely on jQuery), and also supports retina devices.
<script src="layzr.min.js"></script> <img src="optional/placeholder" data-layzr="normal/image" data-layzr-retina="optional/retina/image"> <script> var layzr = new Layzr({ attr: 'data-layzr', retinaAttr: 'data-layzr-retina', threshold: 0, callback: null }); </script>
Updated
So, how to let the server convert a bunch of img in HTML into data-src? In fact, it is very simple, just a few lines of regular rules are enough. For example, in node.js, you can convert img's src into data-src (you can directly press F12 to run it in the browser's Console)
var html = '包含 <img src="http://ourjs.com/img/weixin.jpg"> 的HTML' html = html.replace(/<img[^>]+>/g, function(imgstr, idx) { imgstr = imgstr.replace(' src=', ' data-src=') return imgstr })