【问题标题】:Execute Js code until the document is ready执行Js代码,直到文档准备好
【发布时间】:2013-09-30 17:28:05
【问题描述】:

在文档准备好之前继续执行 JS 代码(每 100 毫秒,在 m 的情况下)的最佳方式是什么。

setInterval(function() { 
   xajax_updateLoader();
}, 100);

一个文件准备好了。执行应该停止。

【问题讨论】:

  • 不使用$(document).ready有什么具体原因吗?
  • 我不想在文档准备好后执行代码,而是在文档准备好之前继续执行它

标签: javascript jquery dom document setinterval


【解决方案1】:
var updateInterval;
$(function(){
 updateInterval= setInterval(function() { 
   xajax_updateLoader();
}, 100);
});

$(windows).load(function(){
    clearInterval(updateInterval)
});

【讨论】:

    【解决方案2】:
    var interval = setInterval(function() { ... }, 100);
    window.onload = function() { clearInterval(interval); }
    

    这会清除 onload 事件的时间间隔。

    【讨论】:

      【解决方案3】:
      var handle = setInterval(function() { 
         xajax_updateLoader();
         if (jQuery.isReady) {
             //DOM is ready
             clearInterval(handle);
         }
      }, 100);
      

      【讨论】:

        【解决方案4】:

        像这样

        domReady = false;
        
        var ctx = setInterval(function() {
         if (domReady === true)
         {
          clearInterval(ctx);
         }
         // your code here
        }, 100);
        
        if (typeof document.addEventListener !== 'undefined') // chrome / safari / firefox
        {
         document.addEventListener("DOMContentLoaded", function(){
          domReady = true;
          document.removeEventListener('DOMContentLoaded');
         }, false);
        }
        else if (typeof document.attachEvent !== 'undefined') // IE
        {
         document.attachEvent("onreadystatechange", function(){
          if ( document.readyState === "complete" )
          {
           document.detachEvent( "onreadystatechange", arguments.callee );
           domReady = true;
          }
         });
        }
        

        【讨论】:

          【解决方案5】:

          使用clearInterval()

          var interval = setInterval(function() { ... }, 100);
          $(document).ready(function(){
           clearInterval(interval);
          });
          

          【讨论】:

            最近更新 更多