Skip to content

Instantly share code, notes, and snippets.

@dhigginbotham
Last active June 2, 2017 04:46
Show Gist options
  • Save dhigginbotham/a2a5d0ffe98876bc37d3686bf3183aa0 to your computer and use it in GitHub Desktop.
Save dhigginbotham/a2a5d0ffe98876bc37d3686bf3183aa0 to your computer and use it in GitHub Desktop.
var latentImages = (function(w,d) {
var state = {};
state.dom = [];
function eventWrapper(type, name, obj) {
obj = obj || window;
var running = false;
function func() {
if (running) { return; }
running = true;
w.requestAnimationFrame(function() {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
}
obj.addEventListener(type, func);
}
function viewportVisible(elem) {
var rect = elem.getBoundingClientRect();
var html = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight) &&
rect.right <= (window.innerWidth || html.clientWidth)
);
}
function collectDom() {
var images = d.querySelectorAll('[data-latent-image]');
images = Array.from(images);
state.dom = images.map(function(image) {
return {
elem: image,
loaded: false,
src: image.getAttribute('data-latent-image'),
};
});
}
function processEligibleImages() {
return state.dom
.filter(function (x) { return x.loaded === false; })
.filter(function (x) { return viewportVisible(x.elem); })
.reduce(function(obj, elig) {
elig.elem.setAttribute('src', elig.src);
elig.loaded = true;
return obj;
}, {});
}
function init() {
collectDom();
processEligibleImages();
w.addEventListener('optimizedScroll', processEligibleImages);
}
eventWrapper('scroll', 'optimizedScroll');
d.addEventListener('DOMContentLoaded', init);
return state;
})(window, document);
@justsml
Copy link

justsml commented Jun 1, 2017

Nice inclusion of the visibility check 👍

Edge cases:
Opacity
Muliple nested scroll areas. Will cause weird shit with this approach.
Obscured absolute/relative positions, similar to nested issue

Also Scroll event has new api features for this use case. All new browsers i think as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment