I have a JSON file referencing about 300 images used in an animation displayed within my Wordpress theme. In my header.php, I'm using the following jQuery to preload all images on DOM load.
function preload(images) {
jQuery(images).each(function () {
jQuery('<img />').attr('src',this).appendTo('body').css('display','none');
});
}
jQuery(document).ready(function() {
preload([
"<?php bloginfo('template_directory'); ?>/library/images/img001.jpg",
"<?php bloginfo('template_directory'); ?>/library/images/img002.jpg",
//about 300 more...
]);
});
The issue is the images are 900x400px so it takes about 30 seconds for all 300 HTTP requests to go through. I'm thinking I could decrease load time if I load images with just one HTTP request. Is this possible? Thanks in advance.
The reason it takes 30 seconds is because you're trying to load 300 images. No amount of optimization will make that a reasonably fast task. You need to rethink your process. For example, you could:
There's absolutely zero need to load 300 large images like that all at once.
Yes it is possible using sprites (No, not the soda). This is when images are packed into one big image.
You can check out PHP's GD library to generate the compiled image for you. Of course, compile once in advance, not every request or it will kill your server.
Taking it to the extreme, you can send the images as a base64 string. That way, the string can be compressed on the server and decompressed on the client with an algorithm like LZW. To add to that, you can apply GZIP on transport.
On the client side, you receive the image as one big image. If you encoded them in base64, you can use the data URI scheme to display the image using the base64 string.
After all that, you can animate the images using the spriting technique, moving the images per frame.
Additional tips:
compress the images using something like Adobe Fireworks:
Split the animation into sections. This technique was used on Google's mother's day doodle, where the animation was split into parts and not per frame.
In order to accomplish one single HTTP request you'd need to base64_encode the files and send them as a a json_encoded list for example. And on the client side do something like:
That would increase the volume of data by 33%, and it would also mean that the images you will be showing are fully loaded into memory, that's 300*900*400*1.33*4 = 0.535100698GB