0

I have an image with set src attribute.

I would like to replace image, but connection with the server is slow and time that it takes to load a new image is not negligible.

Is there possibility to create internal Image object, set kind of "onLoadListener" on it, load an image and then set it to original image src attribute?

2
  • It is possible, but it depends on the caching settings of the client. If caching is turned off completely by the client, you'll have a doubled request count. (one for the attempt to preload an image, one for the actual display) (using Image) Commented Oct 13, 2010 at 14:42
  • Fortunately caching is enabled in my use case :) Commented Oct 13, 2010 at 14:44

1 Answer 1

2

You can pre-load images in JavaScript like this...

myImage = new Image();
myImage.onload = function () { alert("Loaded"); };
myImage.src = "logo.gif";

You can put the logic to pop the image on the page instead of alert-ing.

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

2 Comments

But when my connection is slow user will see empty Image for a while. So I should load Image like this and set myActualImageOnPage.src = myImage.src
@pixel yes, he means to change the src on your real element during the onload method of your dummy image object.

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.