Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of setting img src to unchanged value?

If I have an img tag like

<img src="example.png" />

and I set it via

myImg.src = "example.png";

to the same value again, will this be a no-op, or will browsers unnecessarily redraw the image? (I'm mainly interested in the behaviour of IE6-8, FF3.x, Safari 4-5 and Chrome.)

I need to change many (hundreds of) images at once, and manually comparing the src attribute might be a little bit superfluous - as I assume, that the browser already does this for me?

like image 859
Chris Lercher Avatar asked Aug 28 '10 21:08

Chris Lercher


People also ask

What does img src => do?

The img src stands for image source, which is used to specify the source of an image in the HTML <img> tag.

Can you change img src?

Change Img src If you'd like to replace an image on your website, then you can simply change the image file path or URL in its source attribute. You can change this attribute at any time. It's important to note that the new image inherits the height and width attributes of the original image.

What is the correct format of src attribute?

Example: src="img_girl. jpg". If the URL begins with a slash, it will be relative to the domain. Example: src="/images/img_girl.


1 Answers

Don't assume the browser will do it for you. I am working on a project of similar scale which requires hundreds of (dynamic-loading) images, with speed as the top priority.

Caching the 'src' property of every element is highly recommended. It is expensive to read and set hundreds of DOM element properties, and even setting src to the same value may cause reflow or paint events.

[Edit] The majority of sluggishness in the interface was due to all my loops and processes. Once those were optimized, the UI was very snappy, even when continuously loading hundreds of images.

[Edit 2] In light of your additional information (the images are all small status icons), perhaps you should consider simply declaring a class for each status in your CSS. Also, you might want to look into using cloneNode and replaceNode for a very quick and efficient swap.

[Edit 3] Try absolutely-positioning your image elements. It will limit the amount of reflow that needs to happen, since absolutely-positioned elements are outside of the flow.

like image 189
Tim Avatar answered Oct 26 '22 17:10

Tim