开发者

Check (from bookmarklet) whether page is loaded?

开发者 https://www.devze.com 2023-01-27 00:09 出处:网络
I\'m writing a bookmarklet javascript. The problem here is that it can be invoked by user before and after s开发者_运维知识库ome page has finished loading. I want to ensure that the sript is run only

I'm writing a bookmarklet javascript. The problem here is that it can be invoked by user before and after s开发者_运维知识库ome page has finished loading. I want to ensure that the sript is run only after the page has finished loading. How to do that?


One way for checking if document has loaded, is to check the document.readyState property. IE, Firefox 3.6+, Webkit and Opera support it.

if (document.readyState === "complete") {
    // do sth
}

Another thing is, if you want to wait for the document to load. In that case you have to listen to some events, like DOMContentLoaded on document, load on window or readyStateChange on document.


Hooking a function to the document's ready/load function ensures nowhere in your code can be executed before the DOM is loaded.

<html>
<body onload="documentLoad()">
    <script type="text/javascript">

    function documentLoad() {
        alert("Document is ready now.");
    }

    </script>
</body>
</html>

If you want to use jQuery, you can use a very short-hand method to attach all your code to the ready function.

$(document).ready(function() {
    // All code in here - will trigger when DOM is loaded.
}

And here is an even shorter short-hand method, using jQuery, to achieve the same.

$(function(){
    // All code in here - will trigger when DOM is loaded.
});


<body onload="start()">
</body>

In the function start the DOM is guaranteed to be loaded.


var firstLoad = true;
$(document).ready(function(){
    if ( firstLoad ){
        firstLoad=false;
        //your code to run once
    }
});


Most answers here are answering how to attach a function to the document ready function, which isn't what davidgale is asking...

The document object has a property of readyState which will be set to "complete" when it has finished loading.

<html>
<body>

   <script type="text/javascript">

   function someFunction() {
      // Called various times throughout page's life.

      if(document.readyState == "complete") {
         // Perform DOM actions - will only attempt after DOM is loaded.
      }
   }
   </script>

</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消