Preloading an image or sprite and make it load fast

Recently we did a new re-design for leadingcourses.com. One of the goals was to make the site fast. As I am a (freelance, yes, I can be hired 😉 ) front-end developer, I wanted the front-end to be as fast as possible with as little effort as possible.

I already read a lot of articles written by Steve Souders and Stoyan Stefanov about site speed. A lot of stuff went in my head for that, and now I will just type it out so it is written down.

In this post the steps I took to make our sprite load faster.

Steps I took

Creating the sprite

The first thing I did is move all the assets to 1 sprite. To be honest 1/2k more or less I do not consider as an issue as I wanted to do as less effort as possible, but with the best result. I created a sprite (png) and I did not pay attention where to place certain images, as long as it was convenient for me to develop.

Reducing the size of the png

There is a lot of metadata and other crap in the image that can be removed quite easily, I was looking into a tool which could handle that. There are several available, but for my sprite, punypng gave me the best result, smaller and no loss in quality. The weight loss is more than 1 or 2k, which is great of course ;-). So instead of optimising the image and make development a bit harder, I used punypng to make my file smaller.

Preloading the image.

So as I told before, I read a lot about site speed, but I had to digg a bit to find the article which explained the solution I also used.

Basically the idea is, add an image with javascript to the head of the document.

<script>
setTimeout(function(){
    var s = document.createElement('image');
    s.src =  'sprite.png';
    (document.getElementsByTagName('head')[0]).appendChild(s);
},5);
</script>

But there is one problem with this. Printing. Yes, and only printing in IE. It seems that when printing a document, yes it actually happens, all ‘normal’ elements are shown by default, but the special elements like <script> and <link> are hidden. An image is visible in the print.

This is, of course, something we don’t want. We all love our trees and our wallet, so I had to figure out what was the issue. So I tried styling the element with CSS from my css-file. For some reason, unknown by me, but maybe known by others, it did not work.

What I then did was adding a style attribute to the element to be created which sets a height to 1px. The reason I do not display: none, is that I do not know what happens with it, does it gets cached? giving height: 0 will trigger antivirus software to scream about the page in some cases, so… I made it 1px. 1px won’t be noticed in our case, as the first pixel mainly is transparent.

Final code

<script>
setTimeout(function(){
    var s = document.createElement('image');
    s.src =  'sprite.png';
    s.style.height = 1;
    (document.getElementsByTagName('head')[0]).appendChild(s);
},5);
</script>

Speak Your Mind

*