Created
May 31, 2013 14:28
-
-
Save aebsr/5685348 to your computer and use it in GitHub Desktop.
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
define (require) -> | |
$ = require 'jquery' | |
$(document).ready -> | |
deferrableImages = $("img[data-src]").toArray() | |
# deferrableImages = $("img[data-src]").toArray() | |
loadImage = ($el, $fn) -> | |
$($el).attr "src", $($el).attr "data-src" | |
$($el).removeAttr "data-src" | |
(if $fn then $fn() else null) | |
elementInViewport = ($el) -> | |
$rect = $el.getBoundingClientRect() | |
$rect.top >= 0 and $rect.left >= 0 and $rect.top <= (window.innerHeight or document.documentElement.clientHeight) | |
# Load images as neccesary | |
findImagesToLoad = -> | |
console.log 'looking...' | |
imagesToCheck = deferrableImages[..] | |
imagesToRecheck = [] | |
while imagesToCheck.length | |
el = imagesToCheck.pop() | |
if elementInViewport el | |
loadImage el | |
else | |
imagesToRecheck.push el | |
deferrableImages = imagesToRecheck | |
unless deferrableImages.length | |
$(window).unbind 'scroll', findImagesToLoad | |
findImagesToLoad() | |
$(window).bind "scroll", findImagesToLoad |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment