php - CSS图像的延迟加载
问题描述
我有以下适用于 <img> 的延迟加载函数。
<script>
document.addEventListener("DOMContentLoaded", function() {
var lazyloadImages;
if ("IntersectionObserver" in window) {
lazyloadImages = document.querySelectorAll(".lazy");
var imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
image.classList.remove("lazy");
imageObserver.unobserve(image);
}
});
});
lazyloadImages.forEach(function(image) {
imageObserver.observe(image);
});
} else {
var lazyloadThrottleTimeout;
lazyloadImages = document.querySelectorAll(".lazy");
function lazyload () {
if(lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function() {
var scrollTop = window.pageYOffset;
lazyloadImages.forEach(function(img) {
if(img.offsetTop < (window.innerHeight + scrollTop)) {
img.src = img.dataset.src;
img.classList.remove('lazy');
}
});
if(lazyloadImages.length == 0) {
document.removeEventListener("scroll", lazyload);
window.removeEventListener("resize", lazyload);
window.removeEventListener("orientationChange", lazyload);
}
}, 20);
}
document.addEventListener("scroll", lazyload);
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);
}
})
</script>
该函数不是我的,我需要知道如何修改它以适用于下一个从 CSS 加载图像的示例:
<div class="col-md-2 col-sm-3 col-xs-4 photo" style="padding: 2.5px">
<span onclick="window.location.href=\''.$link.'\';"
class="thumbnail"
role="img"
style="background-image: url(\''.$image.'\'); cursor: pointer; margin: 0; margin-top: 5px;"
aria-label="' . $row["topic_title"] . '"
title="'.$row['topic_title'].'">
</span>
<center>
<p class="name" style="margin 0 2px; color: white; margin-top: 5px;">
<a href="'.$link.'" title="'.$row['topic_title'].'">' . $title . '</a>
</p>
</center>
</div>
在有 24 个 gif 的页面上,页面加载速度相对较慢,我想更改它。我可以使用 <img> 正常加载图像,但我希望页面更加动态,因为使用 span 我有不同的 temathic。
这是我设法完成脚本的方法,它可以正常工作。希望有人会发现它有用。
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
var imageUrl = "url" + "(" + "'" + image.src + "')";
entry.target.style.backgroundImage = imageUrl;
image.classList.remove("lazy");
imageObserver.unobserve(image);
}
解决方案
推荐阅读
- php - PHPDeployer:根据主机为本地任务设置变量?
- c# - 执行处理程序的子请求时出错(仅在服务器上部署的应用程序)
- c# - 在 NumericUpDown 值更改时启用 GroupBox
- azure - 函数应用部署得到 403 错误和扩展代码 01020
- typescript - 从没有“as const”的数组创建类型元组
- javascript - JavaScript replace() 方法替换错误字符
- tensorflow - Keras model_to_estimator 不在 estimator.train 上记录指标,而是在 estimator.evaluate 上记录
- swift - 当视图控制器从 nib 文件加载时,以模态方式在当前上下文中呈现视图控制器
- mysql - MariaDB/Galera:将 MariaDB 10.4 节点连接到 MariaDB 10.1 集群是否安全?
- android - Cordova 不断用默认的 Hello World 应用程序替换我的代码