Search code examples
javascriptjquerycssimagebackground-image

Preload all CSS images while showing a preloader


I have a website heavily loaded with images. It's quite unattractive to see the images coming up slowly. I've seen a few websites show a preloader which hides that ugly loading phase. I'm not talking about the <img /> tag here, but I'm talking about CSS background-images.

I do not understand how to achieve this effect using JavaScript and/or jQuery.

P.S: I also seeking links to plugins if there are any available.


Solution

  • Start of with setting the css:

    #myElement
    {
        background-image: url('loading.gif');
    }
    

    Then use the following javascript function:

    function loadImage()
    {
        var img = new Image;
        img.src = "http://path/to/img";
        img.onload = function() 
        {
            var myElement = document.getElementById("myElement");
            myElement.style.backgroundImage = "url('" + this.src + "')";
        }
    }
    

    fire the function in the body onload like this:

    <body onload="loadImage();">
    

    or add it to another init script which fires from here.

    Hope this will get you going!