1

I'm loading image tags via AJAX and inserting them with the conventional .html(content) function in jQuery alongside a bunch of other HTML. However, this question still applies if you're loading a page from scratch. Now, I have a background image placeholder to be put there while the image loads. I want this background image to go away when the image loads.

Problem:

If I attach a conventional .load(function) event listener, I am concerned that the image might load before the hook is applied (putting the hook in a small JS <script> right after the image instead of in a $(function(){}) block might help a bit). I have yet to encounter such behaviour, but I know of nothing in the specification that prevents this from happening (since the image tag ought to be fully parsed before the hook is applied).

My current solution. Put the command in an inline onload= property within the image tag.

Is there a better way?

2 Answers 2

5

Up until a week or so ago I would have been lost too. Thankfully this answer to another question will help you out:

Basically put this in $():

$(function(){ 
   var img = $("#idofimage").load(function () { 
      /* your magic to swap out placeholder */ 
   });

   if (img[0].complete) {
     // Trigger the load handler if the image
     // is already loaded
     img.trigger('load');
   }

});
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh... so complete is the flag I'm looking for. I've been searching up and down the DOM spec and must have missed it! Cheers.
-1

You don't need jQuery for this, you can do it with CSS.

.my-img-loader-class { background:url('placeholder-or-progress'); }

Or if you don't want to change your HTML:

#container img { background:url('placeholder-or-progress'); }

To show placeholders while images are loading in a specific div.

The way it works is the image element will show the placeholder image as its background, and when the src loads it will appear above the placeholder, so as to replace it nicely.

1 Comment

This is what I'm already doing. I want the background to disappear once the image loads. Otherwise, a transparent image will show the background. @Doug Neiner's work did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.