how to load image in background?

16,242

Solution 1

Just make a new image via javascript, and only show the image after the onload has fired. This will make sure you don't see any partial rendering of the image.

Live Demo

    var curImg = new Image();

    curImg.src = "url to your image";
    curImg.onload = function(){
        // do whatever here, add it to the background, append the image ect.
        imgHolder.appendChild(curImg);   
    }

Solution 2

You can play with 2 img tags. img1 shows the first image, while img2, is hidden, and loads the next image.

At the onload event of img2, you can hide img1, and show img2.

And load the next image with img1, and so on.

Solution 3

link rel="prerender" might do the trick.

http://www.catswhocode.com/blog/mastering-html5-prefetching

Share:
16,242
Ashish Agarwal
Author by

Ashish Agarwal

Updated on June 08, 2022

Comments

  • Ashish Agarwal
    Ashish Agarwal almost 2 years

    Problem: I am creating an album.So on every press of

    time "NEXT" button I am loading new Images. What I want to achieve is, I want to switch from old image to new image only once the new images has been downloaded fully from server.

    Actually I dont want to show partial images while loading.
    Is there any solution?

    PS SIMILAR QUESTION but this is for Iphone. I need for browser?

  • Ashish Agarwal
    Ashish Agarwal almost 13 years
    It worked for me.Thanks. I also 1 more useful links, that's for others csgnetwork.com/directjsimageobj.html
  • Martin
    Martin about 11 years
    Interesting answer, but I don't think this would be useful in this case. The asker needs it for a gallery. If you add more <link> tags to the head with rel="prerender" through JS, would it work as the asker is intending?
  • R D
    R D over 7 years
    Note that at least chrome will display the "web page loading spinner" in its interface until the image is loaded. As a workaround, wrap the snippet above in window.onload.
  • newdark-it
    newdark-it over 6 years
    The image in your example is no longer available. realbollywood.com/news/up_images/big-pictures5708.jpg
  • Loktar
    Loktar over 6 years
    @Brandt haha so you down vote it? Apply any other image to it in the fiddle, the code in the answer doesn't require that specific image.
  • newdark-it
    newdark-it over 6 years
    Sorry was looking for answer and when I went to the demo it did not work so I assumed the code did not work. That is why I down voted. After looking into it found it was a bad image and posted a comment. Won't let me undo the down vote however until 13 more hours. Hope that helps explain.