jquery页面加载延迟

时间:2011-03-14 15:05:32

标签: jquery load external

我希望在页面加载了一些延迟后从外部源加载div。

这是我的jquery脚本。发生的事情是首先加载内容然后再加载loader.gif。如何在xx时间后显示来自外部源的内容..?我对.load()函数有所了解但不确定如何实现。

$(window).load(function() {
$('<div id="overlay"><img src="loading.gif" /></div>')
.css('opacity', '0.5')
.insertAfter('body');

window.setTimeout(function() {
$(document).ready(function() {
$('#overlay').remove();
});}, 1000);
$('.body').show();
});

<div id="container">
<div id="header">navigation</div>
<div id="body" class="body">Body</div>
<div id="footer">footer</div>
</div>


#overlay {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
background: gray;
}

.body{display:none;}

#overlay img {
 display: block;
 width: 32px;
 height: 32px;
 position: absolute;
 top: 50%;
 left: 50%;
 margin: -26px 0 0 -26px;
 padding: 10px;
 background: #fff;
 -moz-border-radius: 6px;
 border-radius: 6px;
}

3 个答案:

答案 0 :(得分:1)

你说ajax拉后你的gif正在加载。如果这是你的问题,你可以在加载gif之后调用你的ajax pull,方法是:

yourimg = new Image(); 
yourimg.src = "loading.gif";

yourimg.loadEvent = function(url, image){
    var overlay = $('<div id="overlay" />');
    overlay.append(image).css('opacity', '0.5').insertAfter('body');
    //call whatever you want here. your image is loaded.
}

yourimg.load();

答案 1 :(得分:0)

来自jquery website

The load event is sent to an element when it and all sub-elements have been
completely loaded. This event can be sent to any element associated with a URL: 
images scripts, frames, iframes, and the window object.

你需要在身体加载时展示你的div并将其隐藏起来。我不确定这是不是你问的问题。如果不是setTimeout函数可能就是你想要的那样。

答案 2 :(得分:0)

您的代码中存在一个小问题:

window.setTimeout(function() {
$(document).ready(function() {
...

在此代码中,您将超时设置为执行此操作的函数:

function() {
    $(document).ready(function() {
        $('#overlay').remove();
    });
}

基本上它会等待一秒钟,然后为文档的ready事件添加一个监听器,并在该监听器中执行实际工作。因此,如果在第一秒内触发了就绪事件 - 该函数根本不会执行。

您的代码应如下所示:

$(window).load(function() {
    setTimeout(function() {
        // Do the dom manipulations remove the placeholder
    }, 1000);
});

占位符将在加载事件后一秒钟内删除。请注意,“加载”和“就绪”事件是不同的。并且“load”不保证将解析或呈现DOM。

相关问题