$(document).ready到底保证了什么? [英] What exactly does $(document).ready guarantee?

查看:147
本文介绍了$(document).ready到底保证了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Google的Chrome浏览器中运行我的(相当复杂的)JavaScript / jQuery应用程序,似乎 $(document).ready 会触发,而某些JavaScript文件却没有尚未加载。

Running my (rather complex) JavaScript/jQuery application in Google's Chrome browser, it would appear that $(document).ready fires while some of the JavaScript files have not yet loaded.

相关代码(简化):

在我的HTML文件中

<script>var httpRoot='../../../';var verifyLoad = {};</script>

<script src="../../../globalvars.js"></script>
<script src="../../../storagekeys.js"></script>
<script src="../../../geometry.js"></script>
<script src="../../../md5.js"></script>
<script src="../../../serialize.js"></script>
...
<script src="../../../main.js"></script>

作为每个.js文件的最后一个语句,除了main.js:

As the last statement of each of the .js files except main.js:

verifyLoad.FOO = true; // where FOO is a property specific to the file

例如

verifyLoad.jquerySupplements = true; 

verifyLoad.serialize = true; 

在main.js中:

$(document).ready(function() {
    function verifyLoadTest (scriptFileName, token) {
        if (!verifyLoad.hasOwnProperty(token)) {
            console.log(scriptFileName + ' not properly loaded'); 
        };
    };
    verifyLoadTest('globalvars.js', 'globalvars');
    verifyLoadTest('storagekeys.js', 'storagekeys');
    verifyLoadTest('geometry.js', 'geometry');
    verifyLoadTest('md5.js', 'geometry');
    verifyLoadTest('serialize.js', 'serialize');
    ...
}

令我惊讶的是,我看到其中一些触发器。这与我对 $(文件).ready 的理解不符。我错过了什么?

Much to my amazement, I see some of these trigger. This does not match my understanding of $(document).ready. What am I missing?

推荐答案

当浏览器从头到尾解析HTML文件并将其转换为文件时,会触发文档的ready事件DOM结构。它不以任何方式保证任何其他资源(例如将加载样式表,图像或(在本例中为脚本)。它只引用DOM结构,并且无论页面资源的加载状态如何都会被触发。

The document's ready event is fired when the browser has parsed the HTML file from beginning to end and converted it into a DOM structure. It does not in any way guarantee that any other resources (e.g. stylesheets, images or, as in this case, scripts) will have loaded. It only refers to the DOM structure, and is fired irrespective of the loading status of the page's resources.

如果要等待加载资源,请使用 window 加载事件,只有当页面上的每个元素都加载完毕后才会触发。

If you want to wait for resources to load, use the window's load event, which is fired only when every element on the page has finished loading.

参见:

  • .load
  • .ready

这篇关于$(document).ready到底保证了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆