Preload all CSS images while showing a preloader


Tags: javascript,jquery,css,image,background-image

Problem :

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.

Any help would be highly appreciated.

P.S: I would also appreciate 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!


    CSS Howto..

    How to set a style one a parent element [duplicate]

    how to add css style to dynamically loaded snippet using jquery ajax

    How to get hoverover text to be at the same line-height as the triggering text

    How do you override “-moz-user-select: none;” on a child element?

    How to give different color to draghandle in RangeSlider

    How to create background css div/rounded corners?

    How to increase the gap between text and underlining on my navbar links

    How to wrap two spans into one line with CSS

    How to align items of a list CSS/jquery

    How to detect DOM element position to use different CSS style via CSS selection

    show image in aspect ratio and all image size same height and width

    how to apply css property to my first div class only

    How do I add a custom font to the part of ConvertTo-HTML?

    How do you spin side to side using css3 animation?

    CSS: how to “plot” invisible text over an image?

    How to make two-coloured stripe using CSS?

    How does browser layout adjacent div to a floating div

    How does one style element within a label say?

    how to stop css/jquery rotation

    How to make Firefox button respect padding?

    How do I get Internet Explorer to do a better job displaying images

    How do I post a jsfiddle example of some trouble I'm seeing in Rails?

    How to make the section and aside touch the footer?

    How to remove underline in css for anchors pseudo element in IE

    How to remove string that dosn't have an html tag using CSS

    How can I reposition a DIV with jQuery? [closed]

    show div border when link is clicked

    how does CSS determine which way to animate a transition?

    How to select an item that is into another item using CSS?

    Bootstrap tooltip showing behind modal window