Javascript + HTML - 在后台加载图像(异步?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15813571/
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
Javascript + HTML - load image in the background (asynchronously?)
提问by Mark Schwed
I've found many topics describing javascript image loading but not exactly what I am searching for.
我发现了许多描述 javascript 图像加载的主题,但并不完全是我要搜索的主题。
I am currently loading images in html the normal way, like
我目前正在以正常方式加载 html 中的图像,例如
<img src="images/big-image.jpg">
This results in a webpage where you have empty spaces that are filled with the loading image from top to bottom. In addition I always have to watch the filesize of the image.
这会导致网页上有空白空间,从上到下填充了加载图像。此外,我总是要注意图像的文件大小。
What I want to achieveis that when the page loads, a downscaled version of every image (around 10kb) is shown. When the page is fully loaded, there should be a javascript function which loads the big images in the background and replaces them when they are loaded.
什么我要实现的是,在页面加载时,每幅图像(约10KB)的缩小的版本显示。当页面完全加载时,应该有一个 javascript 函数在后台加载大图像并在加载时替换它们。
I already found a way to do this with javascript but until all images are replaced the browser shows that he is in "loading" state. Is it possible to do the loading task in the background by using asynchronous methods?
我已经找到了一种使用 javascript 执行此操作的方法,但是在替换所有图像之前,浏览器会显示他处于“加载”状态。是否可以使用异步方法在后台执行加载任务?
<img src="small.jpg" id="image">
<script>
<!--
var img = new Image();
img.onload = function() {
change_image();
}
img.src = "small.jpg";
function change_image() {
document.getElementById("image").src = "big.jpg";
}
//-->
</script>
采纳答案by Alex W
Have you tried this?
你试过这个吗?
window.onload = function() {
setTimeout(function() {
// XHR to request a JS and a CSS
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain.tld/preload.js');
xhr.send('');
xhr = new XMLHttpRequest();
xhr.open('GET', 'http://domain.tld/preload.css');
xhr.send('');
// preload image
new Image().src = "http://domain.tld/preload.png";
}, 1000);
};
http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
回答by Mark Schwed
Do you know what is really annoying? If you just miss to add the window.onload function to your own solution and it works as you wanted...
你知道什么是真正令人讨厌的吗?如果您只是想将 window.onload 函数添加到您自己的解决方案中,并且它可以按您的意愿工作...
Thanks for you idea! :D
谢谢你的主意!:D
<img src="small.jpg" id="image">
<script>
<!--
window.onload = function() {
var img = new Image();
img.onload = function() {
change_image();
}
img.src = "small.jpg";
function change_image() {
document.getElementById("image").src = "big.jpg";
}
};
//-->
</script>