Native JavaScript code lazy loading

Source: Internet
Author: User

1. First define the style that needs lazy loading;

Class= "Lazyload"

2. Set the initial transparency to 0.1;

. lazyload{

Filter:alpha (opacity=10); -moz-opacity:0.1; opacity:0.1;

}

3. Place the real address that really needs to be loaded in the DATA-SRC attribute;

src= "lazy loading pictures. png" data-src= "real picture";

4.

Front-end development Zhou Dawei classmate JavaScript code writing:

function Lazyload () {

var lazyload=document.getelementsbyclassname ("Lazyload");

Window.addeventlistener ("Scroll", function () {

SetTimeout (function () {

for (Var i=0;i<lazyload.length;i++) {

var _this=lazyload[i];

var Clientheight=document.documentelement.clientheight | | Document.body.clientHeight;

var Scrolltop=document.documentelement.scrolltop | | Document.body.scrollTop;

if (Clientheight+scrolltop>=offsettop (_this)) {

_this.setattribute ("src", _this.getattribute ("data-src"));

_this.style.opacity= "1";

}

}

},100);

});

}

Get JS code for offsettop and Offsetleft values (compatible)

function OffsetTop (elements) {
var top = Elements.offsettop;
var parent = elements.offsetparent;
while (parent! = NULL) {
Top + = Parent.offsettop;
parent = parent.offsetparent;
};
return top;
};


function Offsetleft (elements) {
var left = Elements.offsetleft;
var parent = elements.offsetparent;
while (parent! = NULL) {
Left + = Parent.offsetleft;
parent = parent.offsetparent;
};
return parent;
};

Native JavaScript code lazy loading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.