Add spinner while new image gets loaded completely

18,397

The easiest way might be to set the CSS background-image property of the images to a loading spinner graphic.

HTML:

<img src="path/to/real/image.jpg" class="loading">

CSS:

img.loading {
    background: transparent url(path/to/loading.gif) no-repeat scroll center center;
}

Once the actual image is downloaded, it covers up the "loading" animated GIF background image.

If you have GIFs or JPGs saved with Progressive display, you'll want to resave those images without that option so the real image is invisible until the full image is downloaded allowing your spinner graphic to show through in the meantime.

Share:
18,397
Marian07
Author by

Marian07

Updated on July 29, 2022

Comments

  • Marian07
    Marian07 almost 2 years

    The role of the script is to change image.jpg with newimage.gif and vice versa when clicked.
    Now i want to add a spinner while the newimage.gif loads.
    Something like on 9gag.com/gif .

    Can someone help me please?

    This is the code: html

    <img src="/image.jpg" id="pic" onclick="change()"/>
    <a id="first" href="/newimage.gif" style="display:none;"></a>
    <a id="second" href="/image.jpg" style="display:none;"></a>
    

    javascript

    function change(){
    var imag = document.getElementById('pic').src;
    var img = imag.slice(-3);
    var img1 = document.getElementById('second').href;
    var imag2 = document.getElementById('first').href;
    
    if(img == 'gif') {
    document.getElementById('pic').src=imag2;
    //    here the newimage.gif changes to image.jpg 
    } else {
    //    here the image.jpg changes to newimage.gif
    //    i think here should be the code that will display a spinner while the image.gif loads completely
    document.getElementById('pic').src=img1;
    }
    }