jQuery onLoad 事件在加载任何内容之前触发

jQuery onLoad event fires before anything loads

本文关键字:任何内 onLoad 事件 加载 jQuery      更新时间:2023-09-26

我知道有类似的问题,但答案对我不起作用(下面的示例(。首先,我的(简化(代码。

.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 开始加载container,JS 代码就会立即触发显示。

loading_screendiv 只有 1 个小图像 (20KB(,containerdiv 总共约为 400KB。

容器div 中有图像,其某些子元素上有背景图像。因此,根据此问题的答案,我将代码更改为$(window).load(function()。但是,这并没有解决问题。

我想我可以执行以下操作 - 一开始甚至不创建容器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立即隐藏,容器立即可见。

您应该看看这个问题的答案: 检测页面是否已完成加载

.load() api 的 jquery 页面解释了以下内容:

与图像一起使用时加载事件的注意事项

开发人员尝试使用 .load(( 快捷方式解决的一个常见挑战是在图像(或图像集合(完全加载时执行函数。有几个已知的警告应该注意。这些是:

  • 它不能始终如一地工作,也不能可靠地跨浏览器
  • 工作
  • 如果图像 src 设置为与以前相同的 src,则在 WebKit 中无法正确触发
  • 它没有正确地冒泡 DOM 树
  • 可以停止为浏览器缓存中已存在的图像触发

它以此示例结束:示例:在页面完全加载(包括图形(时运行函数。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.
}); 

"ready"事件在构建 DOM 时触发,但在加载图像等其他内容之前触发。如果你想要一个真正的"加载"处理程序,那么这样做:

$(window).load(function(){
    //when document loads, hide loading screen and show game
    $('#loading_screen').hide();
    $('#container').show();
})
相关文章: