Skip to content

Instantly share code, notes, and snippets.

@michalkvasnicak
Last active August 29, 2015 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalkvasnicak/71101854cd9d6fbb7cf2 to your computer and use it in GitHub Desktop.
Save michalkvasnicak/71101854cd9d6fbb7cf2 to your computer and use it in GitHub Desktop.
Naive image lazy loading in AngularJS
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