Home >Web Front-end >JS Tutorial >How to implement lazy loading of images?

How to implement lazy loading of images?

coldplay.xixi
coldplay.xixiOriginal
2020-06-30 15:16:173081browse

Method to implement lazy loading: first customize attributes such as [data-imgurl] to store the path of the image; then use js to determine the scrolling position of the interface or whether the image has been loaded; finally load and obtain the attribute [ data-imgurl] value can be assigned to src.

How to implement lazy loading of images?

Method to implement lazy loading of images:

First customize attributes such as [data-imgurl], which stores The path of the image; then use js to determine the scrolling position of the interface or whether the image has been loaded; finally load it and get the value of the attribute [data-imgurl] and assign it to src.

To implement image loading, the specific method is as follows:

$('img').each(function () {//在未触发滚动事件时先判断图片是否已经出现在视窗中,打开页面时先遍历一次
if (checkShow($(this)) && !isLoaded($(this)) ){ loadImg($(this));//加载当前img  } })
$(window).on('scroll',function () {//滚动的触发事件
        $('img').each(function () {//遍历img标签
            if (checkShow($(this)) && !isLoaded($(this)) ){
                loadImg($(this));//加载当前img
            }
        })
    })
function checkShow($img) {};// 定义checkShow函数判断当前img是否已经出现在了视野中,传入img对象
function isLoaded ($img) {};//定义isLoaded函数判断当前img是否已经被加载过了
function loadImg ($img) {};//定义loadImg函数加载图片

1. Determine whether the target label appears in the field of view:

function checkShow($img) { // 传入img对象
        var sTop = $(window).scrollTop();  //即页面向上滚动的距离
        var wHeight = $(window).height(); // 浏览器自身的高度
        var offsetTop = $img.offset().top;  //目标标签img相对于document顶部的位置
        if (offsetTop < (scrollTop + windowHeight) && offsetTop > scrollTop) { //在2个临界状态之间的就为出现在视野中的
            return true;
        }
        return false;
    }

2 . Determine whether the target tag has been loaded:

 function isLoaded ($img) {
        return $img.attr(&#39;data-imgurl&#39;) === $img.attr(&#39;src&#39;); //如果data-imgurl和src相等那么就是已经加载过了
    }

3. Load the target tag:

  function loadImg ($img) {
        $img.attr(&#39;src&#39;,$img.attr(&#39;data-imgurl&#39;)); // 把自定义属性中存放的真实的src地址赋给src属性
    }

Related learning recommendations: javascript Video tutorial

The above is the detailed content of How to implement lazy loading of images?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn