[英]How do you load images in the background and then display the page when complete?
I have an ajax web application, where every 10 seconds I request content from the server. 我有一个Ajax Web应用程序,每10秒钟我从服务器请求内容。 The server sends back HTML with links to images.
服务器发回带有图像链接的HTML。 Right now, I set the innerHTML of a div tag to the HTML returned from the server, which dynamically updates the web page with out reloading the whole page.
现在,我将div标记的innerHTML设置为从服务器返回的HTML,该服务器动态更新网页,而无需重新加载整个页面。
HOWEVER, the problem is, the images load separately after setting the innerHTML causing the application to look funky and slow. 但是,问题是,设置了innerHTML之后,图像会分别加载,从而导致应用程序看起来时髦而缓慢。
How can I have all my images ready and then swap the innerHTML when I have all the resources? 拥有所有资源后,如何准备好所有图像,然后交换innerHTML?
Add an attribute(or data attribute) to the DOM of the images, then with jQuery listen for the "loaded" event change the attribute loaded to be true. 将属性(或数据属性)添加到图像的DOM,然后使用jQuery侦听“ loaded”事件,将属性load更改为true。 Then verify if still images in the queue, if not execute a callback for the complete process.
然后验证队列中是否还有静止图像,如果没有,请执行完整过程的回调。
Markup: 标记:
<img src="img/1.png" class="imgToLoad" loaded="false" />
<img src="img/2.png" class="imgToLoad" loaded="false" />
<img src="img/3.png" class="imgToLoad" loaded="false" />
<img src="img/4.png" class="imgToLoad" loaded="false" />
Pseudocode: 伪代码:
function allImagesLoaded(){
$('#yourmaindiv').show();
console.log('images loaded!');
}
$('img.imgToLoad').load(function(){
$(this).attr('loaded', 'true');
if( $('img.imgToLoad[loaded=false]').length === 0 ){
allImagesLoaded();
}
});
For your images : 对于您的图片:
$(function () {
preload();
function preload() {
var imageObj = new Image(),
images = [];
images[0] = 'img/1.png';
images[1] = 'img/2.png';
images[2] = 'img/3.png';
images[3] = 'img/4.png';
images[4] = 'img/5.png';
for (var i = 0; i < images.length; i++) {
imageObj.src = images[i];
}
}
});
<body>
....
<!--[if IE]>
<div id="preload">
<img src="img/1.png" width="1" height="1" alt="" />
<img src="img/2.png" width="1" height="1" alt="" />
<img src="img/3.png" width="1" height="1" alt="" />
<img src="img/4.png" width="1" height="1" alt="" />
<img src="img/5.png" width="1" height="1" alt="" />
</div>
<![endif]-->
</body>
#preload {
position: absolute;
overflow: hidden;
left: -9999px;
top: -9999px;
height: 1px;
width: 1px;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.