Pull in HTML resource in the background in jQuery
Asked Answered
S

2

4

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

Serenaserenade answered 24/6, 2011 at 21:13 Comment(2)
I got my answer in first and it's essentially the same as what you accepted. Just curious how you chose which answer to accept.Polyhydroxy
@Sparky672, he's probably just shy about using the awesomeness of inlining it.Ingest
S
7

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.

Spinose answered 24/6, 2011 at 21:17 Comment(2)
do you even need the ready() call? why not just run it at execution time?Serenaserenade
@KevinBurke I can't think of any reason why not.Spinose
P
6

You could preload each image...

$(document).ready(function() {
    (new Image()).src  =  '/path/to/myImage.jpg';
});
Polyhydroxy answered 24/6, 2011 at 21:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.