Last active
August 29, 2015 14:04
-
-
Save michalkvasnicak/71101854cd9d6fbb7cf2 to your computer and use it in GitHub Desktop.
Naive image lazy loading in AngularJS
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
angular.module('Demo', []).directive( | |
'imageLazySrc', function($document, $window) { | |
return { | |
restrict: 'A', | |
link: function($scope, $element, $attributes) { | |
function isInView() { | |
// get current viewport position and dimensions, and image position | |
var clientHeight = $document[0].documentElement.clientHeight, | |
clientWidth = $document[0].documentElement.clientWidth, | |
imageRect = $element[0].getBoundingClientRect(); | |
if ( | |
(imageRect.top >= 0 && imageRect.bottom <= clientHeight) | |
&& | |
(imageRect.left >= 0 && imageRect.right <= clientWidth) | |
) { | |
$element[0].src = $attributes.imageLazySrc; // set src attribute on element (it will load image) | |
// unbind event listeners when image src has been set | |
removeEventListeners(); | |
} | |
} | |
function removeEventListeners() { | |
$window.removeEventListener('scroll', isInView); | |
$window.removeEventListener('resize', isInView); | |
} | |
// bind scroll and resize event listener to window | |
$window.addEventListener('scroll', isInView); | |
$window.addEventListener('resize', isInView); | |
// unbind event listeners if element was destroyed | |
// it happens when you change view, etc | |
$element.on('$destroy', function() { | |
removeEventListeners(); | |
}); | |
// explicitly call scroll listener (because, some images are in viewport already and we haven't scrolled yet) | |
isInView(); | |
} | |
}; | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment