当前位置:网站首页>js实现图片懒加载的一个详细方案(引入即可使用)
js实现图片懒加载的一个详细方案(引入即可使用)
2022-06-29 06:41:00 【止水、】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>懒加载</title>
<style> img {
width: 600px; height: 450px; } </style>
<script src="./lazyLoad.js"></script>
</head>
<body>
<img src="" data-src="./imgs/css3.png">
<img src="" data-src="./imgs/css3.png">
<img src="" data-src="./imgs/css3.png">
<img src="" data-src="./imgs/css3.png">
<img src="" data-src="./imgs/css3.png">
<img src="" data-src="./imgs/css3.png">
<img src="" data-src="./imgs/css3.png">
<img src="" data-src="./imgs/css3.png">
</body>
</html>
lazyLoad.js
/** * 在使用一下懒加载的方式之前,图片要设置宽高,不设置宽高,会判断所有图片都在可视区域内 * 整个懒加载方案还需要一下几点的优化: * 1. 可视区域的的元素,目前是浏览器可视窗口,无法对可视区域进行判断 * 2. 事件监听一直存在,目前没有做销毁,考虑在图片全部加载完成后,销毁会导致后续增加的图片就无法触发懒加载 * 3. 对于元素的选中,虽然是通过标签名+属性值,但后续还可进行优化,从而获取更加精准的懒加载目标 */
window.onload = function() {
var imgList = []
var leftInterval = 100 * window.devicePixelRatio // 横向阈值
var heightInterval = 200 * window.devicePixelRatio // 纵向阈值
var throttleTime = 1000 // 节流时间
var debounceTime = 1000 // 防抖时间
var errorSrc = './imgs/wallhaven-1jxw53.jpg' // 图片加载失败的图片
// 判断图片是否出现出现在可视区域的首选方案
var observer = new IntersectionObserver(function(entries) {
entries.forEach(item => {
if (item.isIntersecting) {
// 只处理src=""和没有src属性的图片
if (item.target.src !== null) {
handleImgSrc(item.target)
observer.unobserve(item.target)
}
}
})
})
// 给图片添加src,并处理onerror事件
function handleImgSrc(dom) {
// 已经显示的图片不再处理
if (dom.getAttribute('src')) return
const dataSrc = dom.getAttribute('data-src')
if (dataSrc) {
dom.src = dataSrc
}
dom.onerror = () => {
dom.src = errorSrc
}
}
// 节流函数
function throttle(callback, delay) {
let timer = null
let _this = this
return function(...args) {
if (!timer) {
timer = setTimeout(() => {
callback.call(_this, args)
timer = null
}, delay)
}
}
}
// 防抖函数
function debounce(callback, delay) {
let timer = null
let _this = this
return function(...args) {
clearTimeout(timer)
timer = setTimeout(() => {
callback.call(_this, args)
}, delay)
}
}
// 判断图片是否出现再可是区域额兼容性写法
function isIn(dom) {
const clientWidth = window.innerWidth,
clienHeight = window.innerHeight,
bound = dom.getBoundingClientRect()
return (bound.top < clienHeight + heightInterval && bound.left < clientWidth + leftInterval)
}
// 懒加载
function lazyLoad() {
imgList.forEach(item => {
if (IntersectionObserver) {
observer.observe(item)
} else if (isIn(item)) {
handleImgSrc(item)
}
})
}
// 根据标签name和属性,获取相应的dom
function getElementsByTagNameAndAttribute(tag, attribute) {
const allTags = document.getElementsByTagName(tag)
return Array.from(allTags).filter(item => {
return item.getAttribute(attribute)
})
}
// 这里用一个变量记录,后期优化可以方便清除监听,
// 目前没有设置清楚监听,考虑第一轮图片加载完后,将监听清除后,后面第二轮的图片就无法实现懒加载的功能
var throttleLazy = throttle(lazyLoad, 1000)
var debounceLazy = debounce(lazyLoad, 1000)
function init() {
imgList = getElementsByTagNameAndAttribute('img', 'data-src')
lazyLoad()
window.addEventListener('scroll', throttleLazy, throttleTime)
window.addEventListener('resize', debounceLazy, debounceTime)
}
init()
}
边栏推荐
- tf. to_ int64
- Detailed explanation of top and free commands
- [translation] how Bink drives the digital loyalty transactions of some of the largest banks in the UK
- VMware vcenter/ESXI系列漏洞总结
- 关于KingbaseES临时文件过大问题
- [industrial control old horse] detailed design of PLC six way responder system
- 【深度之眼吴恩达第四期作业班】多元线性回归Linear Regression with multiple variables总结
- Problem solving -- > online OJ (13)
- 【工控老马】西门子PLC s7-300SCL编程详解
- 小白大战指针 (上)
猜你喜欢

【工控老马】西门子PLC s7-300SCL编程详解

从Nacos客户端谈Nacos配置中心

SQL injection bypass (6)

Reasons why the ext.dic file configured in ES does not take effect

【工控老马】洗衣机PLC程序控制系统设计详解

Common MySQL errors and solutions summarized painstakingly (I)

Explanation of swing transformer theory
![Detailed explanation of communication principle between [industrial control old horse] single chip microcomputer and Siemens S7-200](/img/56/b300c0c3606dbc328e301092615bff.jpg)
Detailed explanation of communication principle between [industrial control old horse] single chip microcomputer and Siemens S7-200

Appium automation test foundation ADB common commands (III)

ShapeShifter: Robust Physical Adversarial Attack on Faster R-CNN Object Detector
随机推荐
指针引用数组元素
Matlab Simulink simulation and analysis of power grid sweep frequency
呕心沥血总结出来的MySQL常见错误以及解决方法(二)
Fluent imitates uiswitch
施努卡:视觉定位系统厂家 什么是视觉定位系统
Select distinct on statement in kingbasees
Schnuka: what is visual positioning system? How visual positioning system works
施努卡:3d机器视觉检测系统 3d视觉检测应用行业
Postman pre request
TF.Slim的repeat和stack操作
声波通讯 - 流式数据处理 - 窗口对齐
【深度之眼吴恩达机器学习作业班第四期】逻辑回归编程实现
Appium automation test foundation ADB common commands (III)
【量化投资系统】问题记录及解决方法
SQL injection bypass (6)
【域渗透提权】CVE-2020-1472 NetLogon 权限提升漏洞
Schnuka: 3D visual recognition system 3D visual inspection principle
Detailed explanation of route (Jiuyang Scripture)
tf.to_int64
【工控老马】西门子PLC s7-300SCL编程详解