0
我已經寫了一個腳本來防止所有圖像直接加載到頁面上。防止所有圖像加載,只加載在屏幕上可見的圖像
<div id="domo">
<img src="PUT_YOUR_VALUE"></br>
<img src="PUT_YOUR_VALUE"></br>
<img src="PUT_YOUR_VALUE"></br>
<img src="PUT_YOUR_VALUE"></br>
</div><script>
var images = document.querySelectorAll("#domo img"), item;
[].forEach.call(images, function (item) {
item.setAttribute("data-src", item.src);
item.removeAttribute("src");
});
</script>
現在我希望加載這個圖像,如果他們在視口中可見
我已經嘗試,但失敗了,下面是Java腳本只是添加圖片上面的腳本,並檢查
<script>
var images = document.querySelectorAll("#domo img"), item;
[].forEach.call(images, function (item) {
item.setAttribute("data-src", item.src);
item.removeAttribute("src");
});
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
//these handlers will be removed once the images have loaded
window.addEventListener("DOMContentLoaded", lazyLoadImages);
window.addEventListener("load", lazyLoadImages);
window.addEventListener("resize", lazyLoadImages);
window.addEventListener("scroll", lazyLoadImages);
function lazyLoadImages() {
var images = document.querySelectorAll("#domo img[data-src]"), item;
// load images that have entered the viewport
[].forEach.call(images, function (item) {
if (isElementInViewport(item)) {
item.setAttribute("src", item.getAttribute("data-src"))
item.removeAttribute("data-src")
}
})
// if all the images are loaded, stop calling the handler
if (images.length == 0) {
window.removeEventListener("DOMContentLoaded", lazyLoadImages);
window.removeEventListener("load", lazyLoadImages);
window.removeEventListener("resize", lazyLoadImages);
window.removeEventListener("scroll", lazyLoadImages);
}
}
</script>
我認爲問題在if (isElementInViewport(item)) {
如果你得到的東西請幫助我。