1 回答
TA贡献1852条经验 获得超7个赞
这是我实施的实际解决方案。同时我为图像添加了延迟加载。这是代码,以防它对任何人有帮助:
/**
* this function load the image using an XMLHttpRequest to be able to read the status code from javascript.
*/
function imgLoad(image, onOk, onError) {
var url = image.dataset.src;
var request = new XMLHttpRequest();
request.open('GET', url);
request.responseType = 'blob';
request.onload = function () {
if (request.status === 200) {
onOk(request.response, image);
} else {
onError(image);
}
};
request.onerror = function () {
// if the request fails
onError(image);
};
request.send();
};
/**
* This function is called if the image successfully loads. It just replace the "src" prop and the image is pulled from the cache from the browser.
*/
function onOk(response, image) {
image.crossOrigin = ""; // or "anonymous"
var imageURL = window.URL.createObjectURL(response);
//image.src = imageURL; // to use the blob response
image.src = image.dataset.src; // to use normal src and disk cache
image.onerror = "";
image.classList.remove("lazy");
};
/**
* small helper
*/
function loadImage(image) {
imgLoad(image, onOk, imgError);
};
/**
* wrap up and lazy loading implementation
*/
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
if ("IntersectionObserver" in window) {
let lazyImageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
let lazyImage = entry.target;
loadImage(lazyImage);
lazyImageObserver.unobserve(lazyImage);
}
});
});
lazyImages.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
} else {
// fall back
lazyImages.forEach(function(lazyImage) {
loadImage(lazyImage);
});
}
});
我没有包含“onError”函数,因为它对于我的代码来说非常具体,并且在这里不是非常相关。
- 1 回答
- 0 关注
- 98 浏览
添加回答
举报