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.
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.