Search code examples
javascriptangularjsionic-frameworkregular-language

Preloading all images using $ImageCacheFactory


I have created a mobile application using ionic framework.It contains many images.I need to load all the images with out flickering.So i used $ImageCacheFactory for preloading all the images by refering this blog.

I used below code.The problem is that app contains 100 png images,So i have to refer all the png files.

.run(function($ImageCacheFactory) {
    $ImageCacheFactory.Cache([
        "img/user.png", 
        "img/profile.png",
        "img/logo.png",
        "img/splash.png", 
        "img/map.png", 
        "img/shop.png",
        "img/country.png", 
        "img/place.png"
      ]).then(function(){
         console.log("Images done loading!");
      },function(failed){
          console.log("Error..!!!");
    });
})

Is there any easy method for refering all the png images with single line code(All the images are in www/img folder).Thanks


Solution

  • Create an angular factory as follows

    .factory("$fileFactory", function($q) {
    
      var File = function() {};
    
      File.prototype = {
    
        getEntries: function(path) {
          var deferred = $q.defer();
          window.resolveLocalFileSystemURI(path, function(fileSystem) {
            var directoryReader = fileSystem.createReader();
            directoryReader.readEntries(function(entries) {
              deferred.resolve(entries);
            }, function(error) {
              deferred.reject(error);
            });
          }, function(error) {
            deferred.reject(error);
          });
          return deferred.promise;
        }
    
      };
    
      return File;
    
    });
    

    Then to get list of all file using getEntries()

    .run(function($ImageCacheFactory, $ionicPlatform, $fileFactory ) {
      var fs = new $fileFactory();
      $ionicPlatform.ready(function() {
        fs.getEntries('img').then(function(result) {
          var files = result;
          files = files.unshift({
            name: "[parent]"
          }).map(function(i, v) {
            return 'img/' + v.name;
          });
          $ImageCacheFactory.Cache(files).then(function() {
            console.log("Images done loading!");
          }, function(failed) {
            console.log("Error..!!!");
          });
        })
      });
    });
    

    You need to install dependencies Apache Cordova File

    cordova plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-file.git
    

    Reference : Helpful tutorial