Image Preloader

This is a neat trick which I found (and subsequently used) here.

Basically this is a small jQuery snippet which goes through your stylesheets and looks for images and caches them, so that they are not loaded when the user interacts with a link, logo, overlay window etc.

Here it is:

function preLoadImages () {
    $.get($('link[rel="stylesheet"]')[0].href, function(data){
        r = /url\(['|"]?(\S+\.(gif|jpg|jpeg|png)[^'(]*)['|"]?\)/ig;
        while (match = r.exec(data)){
            var cacheImage = document.createElement('img');
            cacheImage.src = match[1];
        }
   });
}
preLoadImages();
Advertisements

4 thoughts on “Image Preloader

    • jQuery is literally a query syntax on top of javascript. You can easily convert it to straight js with element selectors (though why not use jQuery?), which I’ll leave to you for ‘homework’.

      • JQuery isnt only a query syntax on top of javascript. And it’s slower than javascript. I was just giving you one idea to improve the code. But if you think that a framework is needed because one line of code, go ahead and use it.
        Still a good code snippet, but would be better without the JQuery.
        I didnt meant to be rude, was just giving a hint.

      • Thanks for the comments João. True, my definition of jQuery was over-simplistic, and yes you may incur some overhead compared to vanilla js. I would note, though, that jQuery is very often a component of modern websites and applications, even if a true js framework is being used. However if, you follow the link at the beginning of the post you will find the vanilla js version. My post is simply an adaptation to suit my own use case. So in fact you are free to choose either method 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s