简体   繁体   中英

Which is Faster: Replacing div with img or changing the src attribute of img?

I am implementing an image queue of sorts which downloads x images at a time. Suppose we have a page where there are 30 img tags , and I add the images to my queue from where images are downloaded 5 at a time(value of x). So there is a queue of images to be loaded, and we replace src of the first 5 img's to the intended image links. After one image is loaded, it dequeues another image from the queue and that is then loaded, this continues till all the images are loaded. This ensures that at a time not more than 5 images are being downloaded.
But this obviously slows the pace at which the images on the page are rendered.

I want to know if replacing src's from a default img to the intended link is the fastest way of rendering the images. Ae can also have the case where we have divs in place of a default blank image and we replace the divs with the image when its time to load the images. Would this way be faster, or is the former method the best?

It is generally best to avoid dynamic DOM manipulations (ie dynamic adding/deletion of DOM nodes) as much as possible. Changing the src attribute of an image that's already in the DOM involves no dynamic DOM node addition or change and hence should be preferred. Also, like you said, there is not much difference in performance anyway.

Once a browser has loaded an image the first time, it has the image in memory and doesn't need to load it again every time it's referenced in a stylesheet. So changing background position is the best way.

Use your images like this example.

This is always the fastest way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM