Pull in HTML resource in the background in jQuery

谁说我不能喝 提交于 2019-12-23 12:57:22

问题


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


回答1:


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.




回答2:


You could preload each image...

$(document).ready(function() {
    (new Image()).src  =  '/path/to/myImage.jpg';
});


来源:https://stackoverflow.com/questions/6473832/pull-in-html-resource-in-the-background-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!