Set default image before actual image is loaded

All we need is an easy explanation of the problem, so here it is.

In my application, several images are loaded, however when the view is opened, you can clearly see each image being loaded, by this I mean the top half of the image appears and it keeps increasing till the full image is displayed. I do not want this.

My images are inside an ng-repeat, what i want to do is when the page is loaded all images are set to a default image that comes bundled with the app. Now after my function has returned all new image URLs and those images have been fully loaded then they should replace the default images.

So basically like this:

  1. Open view
  2. Set all images to default.jpg
  3. Get data.
  4. Wait for new images to load fully.
  5. Replace default images with new image URL fetched from the server.

I have never done this before and do not know how to go about it.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can write like this:

<div ng-repeat="user in users">
    <img src="/images/foo/demp/default.png" actual-image="{{user.avatar}}" />

Then you can use a directive like:

myApp.directive('actualImage', ['$timeout', function($timeout) {
    return {
         link: function($scope, element, attrs) {
             function waitForImage(url) {
                 var tempImg = new Image();
                 tempImg.onload = function() {
                     $timeout(function() {
                         element.attr('src', url);
                 tempImg.src = url;

             attrs.$observe('actualImage', function(newValue) {
                 if (newValue) {

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply