Front end lazy loading (easy version)

Front end optimization often optimizes pictures. When there are many pictures on a page, initializing the page and requesting a large number of picture resources will result in poor performance

So lazy loading of images is used,

Lazy loading refers to requesting pictures only when the conditions are met. It can gradually request to avoid a large number of pictures being requested at the same time

The idea of lazy loading is to load pictures only when the browser is in the visible area

1. Set the src attribute of the picture to null during initialization

2. Store src address in custom attribute

3. When the picture enters the field of view, the stored value is assigned to src

The simple code is as follows:

;(function () {
    HTMLElement.prototype.getElementTop = function() {	//Get the distance between the element and the top of the document
        var top = this.offsetTop,
            cur = this.offsetParent;
        while (cur !== null){
            top += cur.offsetTop;
            cur = cur.offsetParent;
        }
        return top;
    };
    var img_top = [],			//The collection of values between the current page picture element and the top of the document
        img_height = [],		//The collection of the height of the current page picture element itself
        layer_element = [];		//There is currently a collection of lazy load flag elements
        element = document.getElementsByTagName("img"),
        view_height = document.documentElement.clientHeight;
    for (var i = 0;i < element.length;i++){
        if (element[i].getAttribute("data-src")){		//Pick out elements with lazy load flag
            layer_element.push(element[i]);
            img_top.push(element[i].getElementTop());
            img_height.push(element[i].offsetHeight);
        }
    }
    document.addEventListener("scroll",function () {	//Scroll event listens for the src attribute assigned to the picture currently in the field of view
        var scroll_top = document.documentElement.scrollTop || document.body.scrollTop;
        for (var i = 0;i < layer_element.length;i++) {
            if (!(scroll_top >= img_top[i] + img_height[i]) && !(scroll_top - 80 < img_top[i] - view_height)) {
                layer_element[i].src = layer_element[i].getAttribute("data-src");
            }
        }
    },false);
})();
When using, you need to attach the "data src" custom attribute in the < img > < / img > tag, whose value is the src value of the picture

Tags: Attribute

Posted on Sun, 24 May 2020 11:46:31 -0400 by nailzfan