I have a website with 500+ icons. I have found that simply letting them load on their own via img.src = "/images/icon1.png" takes far too long and other elements on my site that are further down in the page take like 30 seconds to load due to all the icons loading first. What is the best way to work with a high amount of icons like this? How would you preload it, and preferably not making it into one large sprite! Ideally i would like to server side initialize them into a javascript variable so they can be reused on the client side
Asked
Active
Viewed 280 times
0
-
`img.src = "/images/icon1.png"` ← is that javascript or html? – Ross Oct 24 '16 at 15:36
-
javascript. At the DOM level. Within a javascript function – MrRed Oct 24 '16 at 15:38
-
You can lazy load the images. https://github.com/tuupola/jquery_lazyload – Khorshed Alam Oct 24 '16 at 15:39
-
You could also group them in several smaller category sprites and optimize the image through a https://www.npmjs.com/package/imagemin or lazy load them as previously mentioned – kazandzhiro Oct 24 '16 at 15:44
-
2"preferably not making it into one large sprite" - Well, that *is* the answer. Otherwise, you'll have 500 HTTP requests, no matter how you manage them. – Álvaro González Oct 24 '16 at 15:44
-
hmmm.. Ok ill look into it. Could you reccommend one of the best php sprite generators? – MrRed Oct 24 '16 at 16:02
1 Answers
0
You can preload those images in javascript using:
var img = new Image();
img.src = "/images/icon1.png";
A better method is to use an array like so:
var preloader = ["a.png", "b.jpg", "c.gif"];
var img = [];
for (i = 0; i < preloader.length; i++) {
img[i] = new Image();
img[i].src = preloader[i];
}
Check out these posts:
The definitive best way to preload images using JavaScript/jQuery?
What is the best way to preload multiple images in JavaScript?