Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

javascript - What exactly does $(document).ready guarantee?

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.

The relevant code (simplified):

In my HTML file

<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>

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

e.g.

verifyLoad.jquerySupplements = true; 

verifyLoad.serialize = true; 

In 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');
    ...
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

See:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...