Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull in HTML resource in the background in jQuery

On a page, there is a button. When the button is clicked, a dropdown shows up. The dropdown contains an image. The problem is that the image is not fetched until the user clicks the button.

$("#my_button").click(function(){
    $("#my_dropdown").html("<img src=\"http://mysite.com/image.jpg\" />"); 
});

I'd like to fetch the image when the page loads so it's ready to go when the user clicks the dropdown. How can I do this? I was thinking I could insert the image into the page with display:none set, so it'll get in the cache, or is there a way to load in when the document loads in jQuery?

This is for a Chrome extension, if it makes any difference. I suppose I could put the image in the extension (and that would be faster), but I'm still curious if it's possible to load the image using JS.

Thanks, Kevin

like image 378
Kevin Burke Avatar asked Dec 12 '22 11:12

Kevin Burke


2 Answers

Yes. Just define it as a new image in the ready() call of the page:

$(document).ready( function() {
     var preload = new Image();
     preload.src = "http://mysite.com/image.jpg";
});

Then when you use it, it will already be in the browser's cache. You can use the variable or just reference it the same way you already are.

like image 75
Cfreak Avatar answered Dec 28 '22 08:12

Cfreak


You could preload each image...

$(document).ready(function() {
    (new Image()).src  =  '/path/to/myImage.jpg';
});
like image 33
Sparky Avatar answered Dec 28 '22 06:12

Sparky