Skip to content

Instantly share code, notes, and snippets.

@ryanschuhler
Last active December 16, 2015 08:58
Show Gist options
  • Save ryanschuhler/5409187 to your computer and use it in GitHub Desktop.
Save ryanschuhler/5409187 to your computer and use it in GitHub Desktop.
lazy load javascript idea
var A = AUI();
var lazyLoadObj = A.all('.lazy-load');
var winHeight = window.innerHeight;
var getCumulativeOffset = function (obj) {
var top = 0;
if (obj.offsetParent) {
do {
top += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
y : top
};
};
var lazyLoad = function (arg) {
var scrollY = window.scrollY;
lazyLoadObj.each(
function (e) {
var posY = getCumulativeOffset(this._node).y;
var loadPos = posY - winHeight;
var src = this.getAttribute('src');
var datasrc = this.getAttribute('datasrc');
if (arg == "winHeight") {
argument = winHeight;
loadPos = posY;
}
if (arg == "scrollY") {
argument = scrollY;
}
if (argument > loadPos) {
if (src != datasrc) {
this.setAttribute('src', datasrc);
}
if (!this.hasClass('lazy-loaded')) {
this.addClass('lazy-loaded');
}
}
}
);
};
if (lazyLoadObj.get('length').length > 0) {
lazyLoad ("winHeight"),
A.on(
'scroll',
function () {
lazyLoad ("scrollY");
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment