Обманщик пересечения обманывает?
window.addEventListener("load", function (event) {
var images = document.querySelectorAll('#lazy-img');
//if the browser doesn't support IO
if (!('IntersectionObserver' in window)) {
LoadImagesOldWay(images);
} else {
createObserver(images);
}
}, false);
function createObserver(images) {
var options = {
//root defaults
root: null,
rootMargin: "0px",
//threshold is how much of the element is intersected before firing callback
threshold: .01
};
//create an observer, add the options and callback function
//then add each image to the observer.
var observer = new IntersectionObserver(handleIntersect, options);
images.forEach(function (image) {
observer.observe(image);
});
}
//load the smallest image for old browsers
function LoadImagesOldWay(images) {
images.forEach(function (image) {
var url = image.getAttribute('data-src');
image.setAttribute('src', url);
});
}
function handleIntersect(entries, observer) {
// Loop through the entries
entries.forEach(function (entry) {
//if this entry is intersecting whatsoever
if (entry.intersectionRatio > 0) {
var image = entry.target;
//we get our responsive image set
var url = image.getAttribute('data-src');
//and set them as the actual source
image.setAttribute('src', url);
//we unobserve (Separate) the image entirely
observer.unobserve(entry.target);
console.log('lazy-image loaded!:simpleIO.js line 49 to remove this!');
}
});
}
Мне нравится IO, потому что он чрезвычайно устойчив и открыт.Вы можете лениво загрузить что угодно с помощью наблюдателя на пересечении.
Посмотрите пример с отзывчивыми изображениями на моем github
edit-wow пропустил все полученные вами отрицательные голоса.Не уверен, почему кто-то увидел -1 и подумал, что это должно быть еще хуже.Я думал, что это хороший вопрос, просто плохо сформулированный.Не позволяй им добраться до тебя.: D
Простой-Пересечение-Наблюдатель