I get a json response from a simple API I made,it contains thousands of image urls and sizes around 1.7MB. I am not using any JS framework/libraries. So, what would be efficient way to load the images in DOM?
-
How JSON structure is? Do you need loading or "lazy" (random?) loading? Your question is not clear. – AbsoluteBeginner Apr 14 '21 at 09:47
-
suppose its a large list of urls containing images, I will be running this in localhost, I don't care about order or accessibility or anything, just that it takes too long to load all at once. so I was looking for simples solution. and I found it. – Apr 14 '21 at 10:13
-
It's clearer now. _Lazy loading_ could be the solution, but keep in mind that it's not supported by all browsers: https://caniuse.com/loading-lazy-attr – AbsoluteBeginner Apr 14 '21 at 11:19
2 Answers
You should populate the array with Promise objects which will display some default value at first (a local default-blank.png with a loading spinner for instance, it's up to you) and then, once the promise is solved, you should trigger a callback which will repopulate the object with the externally loaded image.
This can be easily accomplished with vanilla JS. Take a look at this answer, it describes in detail how to do so.

- 696
- 4
- 15
you can get this done by including lazy load to your image tag by setting the loading to "lazy" This is the simplest solution I know, no js required
<img src="your-images-url-goes-here.jpg" loading="lazy" alt="..." />
The loading attribute gives us the option to delay off-screen images and iframes until users scroll to their location on the page. loading can take any of these three values:
lazy: works great for lazy loading eager: instructs the browser to load the specified content right away auto: leaves the option to lazy load or not to lazy load up to the browser.

- 91
- 2
- 8