document.readyState not working in Firefox and Chrome

后端 未结 2 1179
心在旅途
心在旅途 2021-01-07 06:47

In my application, I am calling a method for every 1000ms to check the document readyState. Following is the code which I am using,

var succ         


        
2条回答
  •  天命终不由人
    2021-01-07 07:06

    If you just want to wait until the document is ready there is no need to keep checking - you can listen for the event:

    var whenReady = function(callback) {
      if (document.readyState === 'complete') callback(); // check not already loaded prior to this function being called
      else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback); // for standards compliant browsers (including IE 9+)
      else if (document.attachEvent) document.attachEvent('onreadystatechange', callback); // for IE 8
    };
    
    whenReady(alert('loaded'));
    

    The only downside of this technique is that it only supports IE 8 and later. Libraries such as JQuery offer better legacy browser support and a cleaner syntax:

    $(function() {
      // anything here will execute once the dom is ready
    });
    

提交回复
热议问题