1

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).

1
  • This dup How do you cache an image in Javascript 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). Commented Mar 7, 2016 at 20:57

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Man, what a great answer!
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"; }); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.