使用javascript预加载图像并在准备好时显示 [英] preload image with javascript and display when ready
问题描述
我想显示低分辨率图像,并在完整页面渲染后开始加载高分辨率图像。只有当高分辨率图像被完全加载时,我才想用高分辨率图像替换低分辨率图像。
I want to show a low-res image and start loading the hi-res image after the complete page has rendered. Only when the hi-res image is completely loaded, I want to replace the low-res image by the hi-res image.
我知道我应该使用
$(window).load(function(){
});
但是我该如何开始加载某个图像呢?我怎么知道图像加载的时间?
But what do I do to actually start loading a certain image? And how do I know when the image is loaded?
(我知道lazyload的存在,但是这个图像必须是元素的背景,所以我有使用.css(background-image,var)并且我猜不能使用lazyload。)
(I know about the existence of lazyload, but this image has to be the background of an element, so I have to use .css("background-image", var) and can't use lazyload I guess.)
推荐答案
使用这个用于预加载图片的脚本:
Use this script to preload the images:
<div class="hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
"images-1.png",
"images-2.png",
"images-3.png",
"images-4.png"
)
//--><!]]>
</script>
</div>
然后根据需要在html中使用低分辨率图像,并在需要时更改为高分辨率图像。预加载的图像适合你。
Then use low-res images in your html as you need and change to hi-res images when needed. The preloaded image is there for you.
$(window).load(function(){
$(selector).css('background-image',images[0]);
});
这篇关于使用javascript预加载图像并在准备好时显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!