Commit b20b2c59 by liumengfei

优化产品列表图片懒加载

parent 8f4a0eb2
......@@ -96,7 +96,6 @@ $_helper = $block->getData('outputHelper');
data-container="product-<?= /* @noEscape */ $viewMode ?>">
<?php
$productImage = $block->getImage($_product, $imageDisplayArea);
$baseImageUrl = $productImage->getImageUrl();
$allImage = $_product->getMediaGalleryImages()->getItems();
$hoverImg = '';
......@@ -106,7 +105,6 @@ $_helper = $block->getData('outputHelper');
break;
}
}
if ($pos != null) {
$position = 'left:' . $productImage->getWidth() . 'px;'
. 'top:' . $productImage->getHeight() . 'px;';
......@@ -116,12 +114,9 @@ $_helper = $block->getData('outputHelper');
<a href="<?= $escaper->escapeUrl($_product->getProductUrl()) ?>"
class="product photo product-item-photo"
tabindex="-1">
<?php
$productImageRaw = $imageHelper->init($_product, $imageDisplayArea)->setImageFile($productImage->getFile())->resize($productImage->getWidth(),$productImage->getHeight())->getUrl();
?>
<img class="product-image-photo" src="<?= $productImageRaw ?>" loading="lazy" width="<?= $productImage->getWidth() ?>" height="<?= $productImage->getHeight() ?>" alt="Image">
<?= $productImage->toHtml() ?>
<?php if ($hoverImg): ?>
<img class="hoverImg" width="<?= $productImage->getWidth() ?>" height="<?= $productImage->getHeight() ?>" src="<?= $hoverImg ?>">
<img class="hoverImg" width="<?= $productImage->getWidth() ?>" height="<?= $productImage->getHeight() ?>" data-src="<?= $hoverImg ?>">
<?php endif; ?>
</a>
<div class="product details product-item-details">
......@@ -236,4 +231,44 @@ $_helper = $block->getData('outputHelper');
'item' : <?= json_encode($items, true) ?>
})
</script>
<script>
// 获取所有的图片标签
const imgs = document.getElementsByTagName("img");
// 获取可视区域的高度
const viewHeight =
window.innerHeight || document.documentElement.clientHeight;
// num用于统计当前显示到了哪一张图片,避免每次都从第一张图片开始检查是否露出
let num = 0;
function lazyload() {
for (let i = num; i < imgs.length; i++) {
// 用可视区域高度减去元素顶部距离可视区域顶部的高度
let distance = viewHeight - imgs[i].getBoundingClientRect().top;
// 如果可视区域高度大于等于元素顶部距离可视区域顶部的高度,说明元素露出
if (distance >= 0) {
// 给元素写入真实的src,展示图片
imgs[i].src = imgs[i].getAttribute("data-src");
// 前i张图片已经加载完毕,下次从第i+1张开始检查是否露出
num = i + 1;
}
}
}
// 防抖函数
function debounce(fn, delay = 500) {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.call(this, args);
}, delay);
};
}
// 是的页面初始化是加载首屏图片
window.onload = lazyload;
// 监听Scroll事件,为了防止频繁调用,使用防抖函数优化一下
window.addEventListener("scroll", debounce(lazyload, 600), false);
</script>
<?php endif; ?>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment