Javascript method to implement lazy loading of images
前言
网络上各大论坛,尤其是一些图片类型的网站上,在图片加载时均采用了一种名为懒加载的方式,具体表现为,当页面被请求时,只加载可视区域的图片,其它部分的图片则不加载,只有这些图片出现在可视区域时才会动态加载这些图片,从而节约了网络带宽和提高了初次加载的速度,具体实现的技术并不复杂,下面分别对其说明。
Web 图片的懒加载就是通过读取img元素,然后获得img元素的data-src(也可以约定为其他属性名)属性的值,并赋予img的src,从而实现动态加载图片的机制。
这里需要注意的是: img在初始化的时候不要设置src属性,因为即使设置 src='' 浏览器也会尝试加载图片。
一个简单的图片懒加载共涉及两个方面
1. HTML 约定
我们首先需要给准备实施懒加载的img元素添加指定的class 这里为m-lazyload ,同时将img src赋值给 data-src属性。
具体示例为:
<img class="m-lazyload" data-src="imgUrl">
2. JavaScript 实现
动态加载总共分为以下几个步骤,这里每个步骤都将被拆分为独立的函数
1. 添加页面滚动监听事件
window.addEventListener('scroll', _delay, false); function _delay() { clearTimeout(delay); delay = setTimeout(function () { _loadImage(); }, time); }
2. 当触发监听事件时会执行 _loadImage 函数,该函数负责加载图片
function _loadImage() { for (var i = imgList.length; i--;) { var el = imgList[i]; if (_isShow(el)) { el.src = el.getAttribute('data-src'); el.className = el.className.replace(new RegExp("(\\s|^)" + _selector.substring(1, _selector.length) + "(\\s|$)"), " "); imgList.splice(i, 1); } } }
虽然执行了_loadImage函数,但是我们得知道哪些图片需要被加载,这里的判断依据是什么呢?
依据就是判断该图片是否在当前窗口的可视区域内,在这里我们封装一个_isShow函数来实现
function _isShow(el) { var coords = el.getBoundingClientRect(); return ( (coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerHeight || document.documentElement.clientHeight) + parseInt(offset)); }
自此一个图片加载的闭环就形成了
当网页滚动的事件被触发 -> 执行加载图片操作 -> 判断图片是否在可视区域内 -> 在,则动态将data-src的值赋予该图片。
太简单了?
事实就是如此!!!
如此简单,不妨扩展一下
添加一些自定义参数,谁都喜欢自定义,不是吗?
支持iScroll, iScroll是一个高性能,资源占用少,无依赖,多平台的javascript滚动插件。
这里我们做了些优化
图片加载后移除选择器,避免重复判断。
缓存img元素结合,减少dom元素查询性能损耗
扩展prototype添加getNode方法,支持分页数据懒加载(由于我们之前缓存了dom元素)
OK!说了这么多,show me the code 吧!
(function () { var imgList = [], // 页面所有img元素集合 delay, // setTimeout 对象 offset, //偏移量,用于指定图片距离可视区域多少距离,进行加载 time, // 延迟载入时间 _selector; // 选择器 默认为 .m-lazyload function _isShow(el) { var coords = el.getBoundingClientRect(); return ( (coords.top >= 0 && coords.left >= 0 && coords.top) <= (window.innerHeight || document.documentElement.clientHeight) + parseInt(offset)); } function _loadImage() { for (var i = imgList.length; i--;) { var el = imgList[i]; if (_isShow(el)) { el.src = el.getAttribute('data-src'); el.className = el.className.replace(new RegExp("(\\s|^)" + _selector.substring(1, _selector.length) + "(\\s|$)"), " "); imgList.splice(i, 1); } } } function _delay() { clearTimeout(delay); delay = setTimeout(function () { _loadImage(); }, time); } function ImageLazyload(selector, options) { var defaults = options || {}; offset = defaults.offset || 0; time = defaults.time || 250; _selector = selector || '.m-lazyload'; this.getNode(); _delay();//避免首次加载未触发touch事件,主动触发一次加载函数 if (defaults.iScroll) { defaults.iScroll.on('scroll', _delay); defaults.iScroll.on('scrollEnd', _delay); } else { window.addEventListener('scroll', _delay, false); } } ImageLazyload.prototype.getNode = function () { imgList = []; var nodes = document.querySelectorAll(_selector); for (var i = 0, l = nodes.length; i < l; i++) { imgList.push(nodes[i]); } }; })();

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
