While recently building a Cordova app using Angular, I had a problem with the images not loading fast enough for my app to look the way I wanted.

When a view loaded, there would be a few millisecond delay and then the images would load, giving it a not so great feel.

After looking around at a few things like templatecache, lazy loading, and image preloading, I came across this blog post by Ben Nadel. This seemed like overkill for what I was trying to accomplish, but the preloader function was exactly what I was looking for, so I stripped it out and implemented it like so:

( Here is a finalized version with a readme. )

Created the preloader factory using the code from Ben’s blog post:

angular

.module('core')

.factory("preloader", function( $q, $rootScope ) {

/* factory code goes here */

}

2. Inject the factory in a controller, directive or service, and set an array of images:

app.controller('MyController', function($scope, preloader) {

$scope.imageLocations = [

"img/one.png",

"img/two.png",

"img/three.png",

...

];

}

3. Call preloader.preloadImages on the array of images:

preloader.preloadImages( $scope.imageLocations )

preloader.preloadImages returns a promise, so you could also handle the promise like so:

preloader.preloadImages( $scope.imageLocations )

.then(function() {

// Loading was successful.

},

function() {

// Loading failed on at least one image.

}

That’s it, you should not have any problems when loading new pages, the images should already be loaded!

Here is my repo. I wish I had found something like this before, so I’m hoping this will help someone in my position looking for something very basic to just preload images in an Angular app!