Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery changing <img> src with $(selector).prop takes a long time

So there's no issue with this code functionality itself. I have something like this:

<div>
    <div><img id="imageToChange" src="/path/image.png" /></div>
    <div id="textToChange">Text</div>
</div>

I have another part of my code, that changes the image src/text with jQuery.

function changeImage() {
    $('#imageToChange').prop('src', '/path/image2.png');
    $('#textToChange').html('New Text');
}

As you may expect, this works exactly as I expect it to. But with 1 quirk.

In all the main browsers (chrome/FF/IE). The image takes a long time to change.

So for example, when I call changeImage(), the text will change instantly, but the image may not change until 1-2 seconds later. (Not large images by any stretch, about ~6KB, and local)

I haven't found anyone else really complaining about it, but what I'm wondering is if there's any way to speed up the changing of the image src? Perhaps a better way to do it?

This is jquery 1.8.0 as well.

Thanks

like image 446
bbedward Avatar asked Oct 04 '12 16:10

bbedward


1 Answers

I have seen this behavior before. The delay is caused by the image not being cached and the subsequent load time. The only solutions I know of:

  1. Preload your images with JavaScript Image objects.
  2. Handle the load event on the image and update the text after the image as loaded. Note jQuery lists some issues to watch out for:

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache

http://api.jquery.com/load-event/

like image 83
jimp Avatar answered Oct 19 '22 02:10

jimp