Skip to content

Instantly share code, notes, and snippets.

@ryanschuhler
Last active March 8, 2023 22:01
Show Gist options
  • Save ryanschuhler/5835241 to your computer and use it in GitHub Desktop.
Save ryanschuhler/5835241 to your computer and use it in GitHub Desktop.
This is a function which can be used to lazy-load images or content onto the page. Essentially you give the respective node the class "lazy-load" and the class "lazy-loaded" will be added once the user scrolls to that node. Also if you give the class to an image and place the "src" in a "datasrc" attribute instead, it will switch it to source wh…
AUI().use(
'aui-base',
function(A) {
var WIN = A.getWin();
var lazyLoadNode = A.all('.lazy-load');
var lazyLoad = function() {
var currentScrollPos = WIN.get('docScrollY');
var winHeight = WIN.get('innerHeight');
if (winHeight == undefined) {
winHeight = document.documentElement.clientHeight;
}
lazyLoadNode.each(
function(item, index, collection) {
if (!item.hasClass('lazy-loaded')) {
var loadPos = item.getY() - winHeight;
var dataOffset = parseInt(item.attr('data-offset'));
if (dataOffset) {
loadPos = loadPos + dataOffset;
}
if (currentScrollPos > loadPos) {
var datasrc = item.attr('datasrc');
var src = item.attr('src');
if (src != datasrc) {
item.attr('src', datasrc);
}
item.addClass('lazy-loaded');
}
}
}
);
};
if (!lazyLoadNode.isEmpty()) {
A.on('scroll', lazyLoad);
A.on('resize', lazyLoad);
lazyLoad();
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment