Last active
December 16, 2015 08:58
-
-
Save ryanschuhler/5409187 to your computer and use it in GitHub Desktop.
lazy load javascript idea
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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