我知道有类似的问题,但答案对我不起作用(如下例)。首先,我的(简化的)代码。
HTML:
<div id="loading_screen">
<img src="<?= base_url()?>images/loading_screen.png" title="The game is loading, please wait.."/>
</div>
<div id="container">
<!-- a whole lot of HTML content here -->
</div>
CSS:
#container{
display:none;
}
JS:
$(document).ready(function(){
//when document loads, hide loading screen and show game
$('#loading_screen').hide();
$('#container').show();
})
想法很简单:我最初显示加载屏幕并隐藏容器
;加载完所有内容后,我会隐藏加载屏幕并显示容器。
但是,它不起作用。一旦 container
div 开始 加载,JS 代码就会立即触发显示。
loading_screen
div 只有一张小图片(20KB),container
div 总共约 400KB。
在容器div中有图片,在它的一些子元素上也有背景图片。所以根据this question的答案我将代码更改为 $(window).load(function()
。但是,这并没有解决问题。
我想我可以执行以下操作 - 一开始甚至不创建容器 div,仅在加载加载 div 后才创建容器 div 及其所有内容。但是,我宁愿不走那条路,容器中有服务器端代码,我必须添加包含等,这是不值得的。我很高兴地相信 20KB 的图像将在 400KB 的内容之前加载这一事实,我只需要让代码在这 400KB 的内容加载完成之前不触发。
编辑:
我将这段代码添加到 JS(在 onload 函数之外)以查看页面加载时发生了什么:
setInterval(function(){
var st1 = $('#loading_screen').css("display");
var st2 = $('#container').css("display");
console.log(st1+" "+st2);
},100);
它一直输出none block
,意思是loading_screen立即隐藏,容器立即可见。
最佳答案
你应该看看这个问题的答案:Detect if page has finished loading
.load()
api 的 jquery 页面解释如下:
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
- It doesn't work consistently nor reliably cross-browser
- It doesn't fire correctly in WebKit if the image src is set to the same src as before
- It doesn't correctly bubble up the DOM tree
- Can cease to fire for images that already live in the browser's cache
以这个例子结束: 示例:当页面完全加载(包括图形)时运行函数。 http://api.jquery.com/load-event/
$(windows).on("load", function() { /// this is deprecated --> $( window ).load(function() {
// Run a function when the page is fully loaded including graphics.
});
关于javascript - jQuery onLoad 事件在加载任何内容之前触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27205230/