Lazy loading is often the solution we use for performance optimization, so let’s implement a wave today.
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<title>Lazy loading</title>
<style>
img {
display: block;
margin: 0 auto 50px;
width: 960px;
height: 540px;
}
.opacity {
animation:.5s ani linear;
-webkit-animation:.5s ani linear;
-moz-animation:.5s ani linear;
}
@keyframes ani {
0% {
opacity: 0;
}
50% {
opacity:.5;
}
100% {
opacity: 1; }}</style>
</head>
<body>
<img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzutb8xegj31hc0u0k77.jpg" alt="">
<img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzutz6y29j31hc0u0ak4.jpg" alt="">
<img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzuu8igyyj31hc0u0qgv.jpg" alt="">
<img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzuug47wrj31hc0u0k2q.jpg" alt="">
<img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzuuowb0hj31hc0u0akx.jpg" alt="">
<img src="" data-src="http://ww1.sinaimg.cn/large/005ODVHQgy1fuzuuyjapsj31hc0u0ths.jpg" alt="">
</body>
<script>
var len = document.getElementsByTagName('img').length;
var img = document.getElementsByTagName("img");
var n = 0; // Store the location where the image is loaded to avoid traversing from the first image every time
lazyload();// When the page is loaded, the image in the viewable area is loaded
// Listen for page scroll events
window.onscroll = function () {
lazyload();
};
// Encapsulates lazy loading functions
function lazyload() {
// Height of visible area
var seeHeight = document.documentElement.clientHeight;
// Height of scroll bar from top
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
for (var i = n; i < len; i++) {
// If the distance from the image to the top is less than the sum of the height of the visible area and the distance from the top of the scroll bar, the image will be displayed
if (img[i].offsetTop < seeHeight + scrollTop) {
if (img[i].getAttribute("src") = ="") {
img[i].setAttribute('class'.'opacity');
img[i].src = img[i].getAttribute("data-src");
}
n = i + 1; }}}</script>
</html>
Copy the code
Welcome to pay attention to my public account “front-end history robbery Road”
Reply keyword e-books, you can get nearly 12 front-end popular e-books.
Reply keywords little Red Book 4th edition, you can get the latest “JavaScript advanced Programming” (4th edition) ebook.
You can also add me to wechat. I have wooed many IT bigwigs and created a technical exchange and article sharing group. Welcome to join.
Author: Vam’s Golden Bean Road
Main area: front-end development
My wechat account is Maomin9761
Wechat public number: the front end of the road through robbery