Using jQuery to implement the principle of lazy loading of pictures

In web pages, pictures are often used, and pictures need to consume a large amount of traffic. Under normal circumstances, the browser will parse the entire HTML code, and then load <img src="xxx">the image tags in order from top to bottom. If the page is very long, the image hidden at the bottom of the page is actually loaded by the browser. If the user does not scroll down the page, they will not see these pictures, which is equivalent to wasting the traffic of the pictures.

Therefore, for e-commerce companies such as Taobao and JD.com with huge traffic, the product introduction page must have a large number of pictures. Therefore, the pictures on these pages are "loaded on demand", that is, the pictures are loaded when the user scrolls the page and displays them. When the network speed is very fast, users cannot perceive the action of lazy loading, which saves traffic and does not affect user browsing.

This article gives a principle of using jQuery to implement lazy loading of images. Its basic idea is: when outputting HTML, do not output directly <img src="xxx", but output the following imgtags:

<img src="/static/loading.gif" data-src="http://真正的图片地址/xxx.jpg"> 

Therefore, the picture displayed on the page is a gif loading animation. When the page scrolls, if the image appears on the screen, use jQuery to replace <img>the srcattribute with data-srcthe content, and the browser will load it in real time.

The JavaScript code is as follows:

// 注意: 需要引入jQuery和underscore
$(function() {
    // 获取window的引用:
    var $window = $(window);
    // 获取包含data-src属性的img,并以jQuery对象存入数组: var lazyImgs = _.map($('img[data-src]').get(), function (i) { return $(i); }); // 定义事件函数: var onScroll = function() { // 获取页面滚动的高度: var wtop = $window.scrollTop(); // 判断是否还有未加载的img: if (lazyImgs.length > 0) { // 获取可视区域高度: var wheight = $window.height(); // 存放待删除的索引: var loadedIndex = []; // 循环处理数组的每个img元素: _.each(lazyImgs, function ($i, index) { // 判断是否在可视范围内: if ($i.offset().top - wtop < wheight) { // 设置src属性: $i.attr('src', $i.attr('data-src')); // 添加到待删除数组: loadedIndex.unshift(index); } }); // 删除已处理的对象: _.each(loadedIndex, function (index) { lazyImgs.splice(index, 1); }); } }; // 绑定事件: $window.scroll(onScroll); // 手动触发一次: onScroll(); 

onScroll()The function needs to be triggered manually at the end, because the scroll event is not triggered when the page is displayed. If the pictures are already in the visible area, these pictures are still in the loading state and need to be triggered manually once before they can be displayed normally.

To test the effect of lazy loading of images, you can select "Network" in the console of the Chrome browser, and change "Online" to "Slow 3G" to simulate the effect of lazy loading of images on a slow network:

lazy-loading-test

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325061916&siteId=291194637