0

This might be a question with no answer.

I want to preload an image in a way that it can be displayed on.click without any loading time following the click.

However I also don't want to increase the load time of the page beeing loaded. So essentially I'm looking for a way to load an image in the background after the onload event and before the user requests to see the image (on.click).

Stefan
  • 5
  • 5
  • This dup [How do you cache an image in Javascript](http://stackoverflow.com/questions/10240110/how-do-you-cache-an-image-in-javascript/10240297#10240297) offers an option that doesn't start the preloading until the other resources in the page are done loading (so as not to slow them down in any way). – jfriend00 Mar 07 '16 at 20:57

2 Answers2

0

After page is full loaded (window.onload event is triggered), you can preload any of image with that code.

var image = new Image();
image.src = 'http://hostname/path/to/image.png'

This code place load image and place it to browser cache.

Dmitriy
  • 3,607
  • 14
  • 23
0

Take a look at this, which will grab the image asynchronously after page is loaded and only show the image element after the image is fully downloaded:

With this HTML:

 <img id="theImg">

and this CSS:

 #theImg {display:none; }

Use this JavaScript so the image loads asynchronously:

 window.addEventListener("load", function(){
        setTimeout(loadImg, 0);
 });

 function loadImg(){
     var i = document.getElementById("theImg");
     i.src = "your path to src";
     i.addEventListener("load", function(){ i.style.display= "inline"; });

 }
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54