Easily preload images in your Angular app

Nader Dabit
Dec 2, 2015 · 2 min read

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. )

  1. 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!

Written by

Developer Advocate at AWS Mobile — Specializing in Teaching and Building React & React Native — http://reactnative.training https://aws.amazon.com/mobile

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade