javascript 如何知道文档是否已加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16643232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:29:03  来源:igfitidea点击:

How to know if document has loaded

javascriptdomload

提问by sachinjain024

I have a piece of JS code which needs to determine if DOM has loaded. I know there are several ways of executing JS code when DOM has loaded like:

我有一段 JS 代码需要确定DOM 是否已加载。我知道在加载 DOM 时有几种执行 JS 代码的方法,例如:

$(document).ready(function() { ... }); // Jquery version

document.body.onload = function() { ... } // Vanila JS way

I am looking for some method which looks like

我正在寻找一些看起来像的方法

function isDOMLoaded() {
    // Do something to check if DOM is loaded or not
    // return true/false depending upon logic
}

PS: Update (Post Answer Accept)I happen to see jquery also use the same approach to check if DOM has loaded. Take a look at the Implementation of jquery.ready() here

PS:更新(接受回答后)我碰巧看到 jquery 也使用相同的方法来检查 DOM 是否已加载。在这里查看 jquery.ready()实现

bindReady: function() {
    if ( readyBound ) {
        return;
    }

    readyBound = true;

    // Catch cases where $(document).ready() is called after the
    // browser event has already occurred.
    if ( document.readyState === "complete" ) {
        return jQuery.ready();
    }

    ...

回答by yeahman

function isDOMLoaded(){
 return document.readyState == 'complete';
}

回答by yeahman

You can use something like this

你可以使用这样的东西

function isLoaded() {
    return (document.readyState === 'ready' ||
            document.readyState === 'complete')
}

Check for readyand completestatus.

检查readycomplete状态。

readyis only there for a short moment but do reflect when the DOM is ready. When the page is completely loaded however the status is changed to 'complete'. If you happen to check only for ready the function will fail, so we also check for this status.

ready只存在一小会儿,但要在 DOM 准备好时进行反映。当页面完全加载时,状态将更改为“完成”。如果您碰巧只检查就绪,该函数将失败,因此我们也会检查此状态。

回答by PSL

How about this?

这个怎么样?

var flgDOMLoaded=false; //Set a global variable
 $(document).ready(function() { 
   flgDOMLoaded= true;
  // Some code
 });

function isDOMLoaded() {
   return flgDOMLoaded; // return it. 
  //You don't need this function at all. You could just access window.flgDOMLoaded
}