js images load effect (delayed loading + waterfall load)

The main job of the effects of the two images loaded
one is encountered more page images when loaded with prompt reading of the effect (in order to verify the correct loading, set up a second load interval)
Another is based on the slip preload position of the block for a picture, in a case where the user does not perceive, to achieve the effect of loading the cascade

A delay in loading

The main idea:

  1. img HTML tag, the presence of the correct address of the data-src attribute, all the pictures to a motion circle image loading is provided as a background

  2. js sequentially reads each IMG, the replacement address data-src in the src and the background removed

  3. Each picture is loaded successfully, the percentage of the progress bar changes accordingly.

  4. If the load is not successful, you are prompted to load the wrong picture.


HTML structure is very simple, it is a div.picList wrapped all img, and then add a simple progress bar div # loadBar

<body>
    <div class="picList">
        <img class="lazy" data-src="pic/compressed/picList1.jg">
        <img class="lazy" data-src="pic/compressed/picList2.jpg">
        <img class="lazy" data-src="pic/compressed/picList3.jpg">
        <img class="lazy" data-src="pic/compressed/picList4.jpg">
        <img class="lazy" data-src="pic/compressed/picList5.jpg">
        <img class="lazy" data-src="pic/compressed/picList6.jpg">
        <img class="lazy" data-src="pic/compressed/picList7.jpg">
        <img class="lazy" data-src="pic/compressed/picList8.jpg">
        <img class="lazy" data-src="pic/compressed/picList9.jpg">
        <img class="lazy" data-src="pic/compressed/picList10.jpg">
    </div>

    <div id="loadBar">
        <div id="loadBarMask"></div>
    </div>
</body>

css (scss use, will automatically add the prefix is ​​compatible with a variety of compile-time)

.picList{
    img{
        width: 100px;
        height: 100px;
        position: relative;

        /*加载失败时显示灰底文字*/
        &:after{
            content: "( ⊙ o ⊙ )加载失败";
            font-size: 6px;
            font-family: FontAwesome;
            color: rgb(100, 100, 100);
            display: flex;
            justify-content: center;
            align-items: center;
            position: absolute;
            top: 0;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: #ddd;
        }
    }
}

.lazy{
    background: url(../pic/loading.gif) center no-repeat;
    border: 1px solid black;
}

#loadBar{
    width: 200px;
    height: 15px;
    background: linear-gradient(90deg,#187103,#81b50b,#187103);
    border: 10px solid white;

    position: absolute;
    top: 150px;
    left: 50%;
    margin-left: -100px;

    #loadBarMask{
        width: 70%;//这个数值显示没有加载成功的图片
        height: 100%;
        background-color: beige;
        position: absolute;
        right: 0;
    }
}

css inside there are two caveats:

  • A duplex is the text that appears when you load a wrong picture on the img after pseudo-classes, when the picture fails to load, and remove the background after gif image, it will display the contents and style of this section.

  • A progress bar style. Write a very simple, mainly a layer with a layer of white and green gradient stacked together. Green indicates Loaded, white indicates not loaded. When displayed, the direct control of the white layer width to that.

js moiety (direct execution loadPicPerSecond () can)

var lazyPic = $('img.lazy');
var loadBarMask = $('#loadBarMask');
var picList = $('.picList');

var activePic = 0;
var totalPic = lazyPic.length;

/*每秒加载一张图片*/

function loadPicPerSecond(){

    lazyPic.each(function(index){

        var self = $(this);

        //console.log(self[0].complete);
        /*img标签已经事先写在html中,所以此时的complete状态全部都是true*/

        setTimeout(function(){

            src[index] = self.attr('data-src');
            self.attr('src',src[index]);
            self.removeClass('lazy');

            //图片获得正确src地址之后,可以执行下面的onload操作
            self[0].onload = function(){

                //加载读条loadBar动画
                countPic();
            }

            //图片获得的src地址不正确时,执行下面的onerror操作
            self[0].onerror = function(){
                /*this.style.background = 'url(pic/compressed/picList18.jpg) center no-repeat';*/
                countPic();
            }

        },1000*index);

    })

}

/*根据onload的执行情况来计算当前的图片加载进度.每onload一次,activePic就增加1*/

function countPic(){

    activePic++;

    var leftPic = totalPic - activePic;
    var percentPic = Math.ceil(leftPic/totalPic*100);//没有加载的图片百分比,和loadBarMask的宽度占比配合

    console.log("已加载"+(100-percentPic)+"%");

    loadBarMask.css("width",percentPic+"%");

    if(percentPic==0){
        $('#loadBar').hide();
    }
}

Are two waterfalls flow load

The main idea:

  1. Listening window scroll case, when the last one is about the picture has been loaded into the window and began to load the image below.

  2. After the image is assumed that all addresses already exists a json data, each read address of the picture 10, which is loaded, is inserted into the end of an existing cascade.

  3. And so forth, until you have loaded all the pictures.


HTML and front part of the same, but the src normal write address.
css exactly the same.

js part

var lazyPic = $('img.lazy');
var loadBarMask = $('#loadBarMask');
var picList = $('.picList');

var scrollTop,
    clientHeight,
    scrollHeight;

var threshold = 200; //最后一张图片距离窗口200px的时候开始加载图片

var src = [];

var activePic = 0;
var totalPic = lazyPic.length;

//待加载的图片数据
var dirtSrc = "pic/compressed/picList";
var picData = {imgSrc:[
    dirtSrc + "20.jpg",
    dirtSrc + "21.jpg",
    dirtSrc + "22.jpg",
    dirtSrc + "23.jpg",
    dirtSrc + "24.jpg",
    dirtSrc + "25.jpg",
    dirtSrc + "26.jpg",
    dirtSrc + "27.jpg",
    dirtSrc + "28.jpg",
    dirtSrc + "29.jpg",
    dirtSrc + "30.jpg",
    dirtSrc + "31.jpg",
    dirtSrc + "32.jpg",
    dirtSrc + "33.jpg",
    dirtSrc + "34.jpg",
    dirtSrc + "35.jpg",
    dirtSrc + "36.jpg",
    dirtSrc + "37.jpg",
    dirtSrc + "38.jpg",
    dirtSrc + "39.jpg",
    dirtSrc + "40.jpg",
    dirtSrc + "41.jpg",
    dirtSrc + "42.jpg",
    dirtSrc + "43.jpg",
    dirtSrc + "44.jpg",
    dirtSrc + "45.jpg",
    dirtSrc + "46.jpg",
    dirtSrc + "47.jpg",
    dirtSrc + "48.jpg",
    dirtSrc + "49.jpg",
]};

//加载次数计数器
var scrollIndex = 0;

$(function(){

    /*监听窗口滚动情况*/
    $(window).on('scroll',function(){

        scrollTop = $(window).scrollTop();//$(window).scrollTop()==document.body.scrollTop
        clientHeight = $(window).height();
        scrollHeight = picList.last().height();//picList.last()[0].clientHeight

        /*目标与窗口的距离达到阈值时开始加载*/
        if(scrollHeight-clientHeight-scrollTop < threshold){
            scrollPic(10);
        }
    })
})

/*根据滚动程度加载图片,每次加载perAmount张*/

function scrollPic(perAmount = 10){

    var totalAmount = perAmount * (scrollIndex+1);

     //考虑到最后一次加载的时候,剩余的图片数量有可能达不到限定的每次加载的数量,这时候需要更改totalAmount的值
    if(totalAmount>picData.imgSrc.length){
        totalAmount = picData.imgSrc.length;
    }
    for(scrollIndex;scrollIndex<totalAmount;scrollIndex++){
        var oimg = new Image();
        oimg.src = picData.imgSrc[scrollIndex];
        picList.append(oimg);
    }

}

Compare anxious to catch is scrollTop, the value of the object height that several values, always remember clearly, therefore, in accordance with js and jquery are written on, the future can be used directly. After the value of the relationship to get, as long as the condition is triggered can be loaded.

Three · Postscript compatibility issues

Runtime get under IE8, found behind img.onload killing function not performed, IE8 retarded to not be completed img.onload = function () {} primary code so it?
Then went to check the information, found that although IE8 idiot, but still not to the incurable mentally retarded.
onload is called, but before the assignment src should be placed.

In simple terms, it is to first tell the browser how to deal with the picture has been loaded, and then let it go Load picture. Avoid loading buffer because the speed is too fast, there is no telling when it finished loading to how to do that it has finished loading. And when onload perform other browsers are read from the buffer to the picture.

Guess you like

Origin www.cnblogs.com/jlfw/p/12498439.html