Determining whether the window has loaded without using any global variables

有些话、适合烂在心里 提交于 2019-11-30 06:54:53

You can use the document.readyState property to check if the document has loaded without listening for any events. It will be set to "complete" check if the document and all subresources are loaded. (This corresponds to the load event.)

function checkLoaded() {
  return document.readyState === "complete";
}

If you only want to check if the document has loaded, without worrying about subresources, you can also check if the property is "interactive".

function checkLoaded() {
  return document.readyState === "complete" || document.readyState === "interactive";
}

This should work in current browsers, but is not supported in older versions of all browsers.

You have 2 events available:

addListener(document, "DOMContentLoaded", function(){});  //Dom parsing is finished
addListener(window, "load", function(){}); //loading of all external stuff is done

You can see a difference in those here

Maybe simply something like this:

<html>
<script>
  var loaded = false;
  function checkLoaded(){
     alert(window.loaded);
  }
</script>
<body onload="window.loaded = true; checkLoaded()">
   Loading window.
   <script>
       checkLoaded();
   </script>
</body>
</html>

This will alert when the window is loaded:

(function(w) {
    //private variable
    var loaded = false;
    w.onload = function() {
        loaded = true;
    };

    w.checkLoaded = function() {
        alert(loaded);
    };
})(window);

You can now call checkLoaded() from any part of your app and it will return true or false.

Does this help ?

<script>
    var loaded = false;
    function checkLoaded(){
        alert(loaded);
        //alert true if window is loaded or alert false
    }
</script>


<body onload="loaded = true;checkLoaded();"> <!-- This should alert true -->
   Loding window.
   <script>
       checkLoaded();// this should alert false;
   </script>
</body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!