Lazy loading images with element directive

In this example below you will see how to do a Lazy loading images with element directive with some HTML / CSS and Javascript

Example that show lazy-load of images using AngularJS element directive.The img load first the thumbnail image with "thumb" attribute.

Thumbnail
This awesome code was written by -kaik-, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright -kaik- ©

Technologies

  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Lazy loading images with element directive</title>
  
  
  
  
  
</head>

<body>

  <html>
  <head>
    <link href="style.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

    <script src="app.js"></script>
  </head>
  
  
  <body>

    <div class="container" ng-app="myApp" ng-controller="main">
      <br/>
      <h4>Simple example for lazy-loading Hi-Res images with element directive</h4>
      <p>The img load first the thumbnail image with "thumb" attribute.</p>
        
      <p>The hi-res images (in "image" attribute) are loaded outside from DOM. When the image is clicked, it's "active-image" attribute changes to TRUE, and then the hi-res image replace the thumbnail image. Click on the image another time, and the thumbnail image will replace the main image another time.</p>
      
      <a href="kaikreations.blogspot.com.es">Visit my blog for more tutorials</a>
      
      <br/><br/>

       <div ng-repeat="image in images" style="vertical-align: top;">
           --------- {{$index}} ---------<br/>

          <my-lazy-image width="200px" height="200px" thumb="{{spinnerURL}}" image="{{image}}" active-image="{{activeImages[$index]}}" ng-click="switchActiveValueOnImage($index)" />

      </div>
 

    </div>


  </body>
</html>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/-kaik-/lazy-loading-images-with-element-directive-JiBgm */

angular.module("myApp", [])
  .controller("main", function($scope) {

      $scope.spinnerURL  = "https://38.media.tumblr.com/bec5933eea5043acf6a37bb1394384ab/tumblr_meyfxzwXUc1rgpyeqo1_400.gif";
  
      $scope.images = ["http://critterbabies.com/wp-content/gallery/kittens/803864926_1375572583.jpg",
                      "http://kpbs.media.clients.ellingtoncms.com/img/news/tease/2014/08/20/Cute_grey_kitten.jpg",
                      "http://upload.wikimedia.org/wikipedia/commons/a/a5/Red_Kitten_01.jpg",
                      "http://www.androscogginanimalhospital.com/blog/wp-content/uploads/2013/12/kitten-photo.jpg",
                      "http://upload.wikimedia.org/wikipedia/commons/d/d3/Little_kitten.jpg",
                      "http://www.sfgov2.org/ftp/uploadedimages/acc/Adoption_Center/Foster%20Kitten%2012007.jpg",
                      "http://upload.wikimedia.org/wikipedia/commons/b/bd/Golden_tabby_and_white_kitten_n01.jpg",
                      "http://fc01.deviantart.net/fs45/f/2009/060/e/e/Kitten_and_Faucet_no__3_by_Mischi3vo.jpg",
                      "http://miriadna.com/desctopwalls/images/max/Grey-kitten.jpg",
                      "http://img1.wikia.nocookie.net/__cb20140227161247/creepypasta/images/f/f0/Cats-and-kittens-wallpapers-hdkitten-cat-big-cat-baby-kitten-sleep-2560x1024px-hd-wallpaper--cat-umizfbaa.jpg"
                      ]


          $scope.activeImages = [false, 
                            false, 
                            false, 
                            false, 
                            false, 
                            false, 
                            false, 
                            false, 
                            false, 
                            false 
     ]

     $scope.switchActiveValueOnImage = function(index)
     {
        $scope.activeImages[index] = !$scope.activeImages[index];
     }
})



.directive('myCenterBg', function(){
  return{
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.css({
        'background-size': 'cover',
        'background-repeat': 'no-repeat',
        'background-position': 'center center',
      });
    }
  }
})
      

.directive('myLazyImage', function(){
  return {
    scope: {},
    restrict: 'E',
    template : "<div my-center-bg></div>",
    link: function(scope, element, attrs) {

      if(attrs.thumb){
        var backgroundImg = attrs.thumb;
      }

      element.children().css({
        'background-image': 'url(' + backgroundImg + ')',
        'width': attrs.width,
        'height': attrs.height,
      });
      
      if(attrs.image){

        scope.img = new Image();

        scope.img.onload = function(){
          if(scope.active){
            element.children().css({
              'background-image': 'url(' + this.src + ')'
            });     
          }
        }

        scope.img.src = attrs.image;

        if(attrs.activeImage)
        {
          scope.active = false;
          attrs.$observe('activeImage', function(isActive){

              scope.active = scope.$eval(isActive);
              if(scope.active){
                element.children().css({
                  'background-image': 'url(' + scope.img.src + ')'
                });     
              }
              else{
                element.children().css({
                  'background-image': 'url(' + backgroundImg + ')',
                });
              }
            
          });
        }
        else
        {
            scope.active = true;
        }
        
      }
    }
  }
  
});

Comments