简体   繁体   中英

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

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

Any help would be highly appreciated.

PS: I would also appreciate links to plugins if there are any available.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM