JQuery - 预加载图像(使用 JQuery/原生 JavaScript/CSS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19717611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery - Preload Images (using JQuery / native JavaScript / CSS)
提问by Matt
I previously asked a question on how to hover on a small image and load an additional image to the right side of the page. I have everything working correctly, but now I want to preload images.
我之前问过一个关于如何将鼠标悬停在小图像上并将附加图像加载到页面右侧的问题。我一切正常,但现在我想预加载图像。
How can I preload an image using JQuery so that I can show it immediately to the user when I want to (without a loading time)?
如何使用 JQuery 预加载图像,以便我可以在需要时立即将其显示给用户(无需加载时间)?
回答by sjkm
You can preload an image quite easily as follows:
您可以很容易地预加载图像,如下所示:
using JQuery
使用JQuery
function preloadImg(src) {
$('<img/>')[0].src = src;
}
preloadImg('http://yoururl/to/the/picture.jpg');
or Native Javascript
或原生 Javascript
function preloadImg(src) {
var img = new Image();
img.src = src;
}
preloadImg('http://yoururl/to/the/picture.jpg');
or Using CSS (no JavaScript required)
或使用 CSS(不需要 JavaScript)
You can also preload images using CSS (and HTML)
您还可以使用 CSS(和 HTML)预加载图像
CSS:
div#preload { display: none; }
CSS:
div#preload { display: none; }
HTML:
HTML:
<div id="preload">
<img src="http://yoururl/to/the/picture1.jpg" width="1" height="1" alt="Image 1" />
<img src="http://yoururl/to/the/picture2.jpg" width="1" height="1" alt="Image 2" />
<img src="http://yoururl/to/the/picture3.jpg" width="1" height="1" alt="Image 3" />
</div>
回答by Mike Thomsen
The easiest way to preload an image would be something like this:
预加载图像的最简单方法是这样的:
function preload(selector, url) {
$('<img/>').attr({
src: url,
height: '1px',
width: '1px'
}).appendTo($(selector)).delay(1000).remove();
}
回答by RodgeDodge
I did it like this.
我是这样做的。
I looked up any hover state images then preloaded the hover state by replacing the -nm (normal) with the -hv (hover)
我查找了任何悬停状态图像,然后通过将 -nm(正常)替换为 -hv(悬停)来预加载悬停状态
The beauty of doing it like this is that there is no hard coding of URLs
这样做的美妙之处在于没有 URL 的硬编码
$(function() {
$(this).find("img[src*='-nm']").each(function () {
$('<img/>')[0].src = this.src.replace(/-nm/, "-hv");
});
})