简体   繁体   English

执行Js代码,直到文档准备就绪

[英]Execute Js code until the document is ready

What's the best way to keep executing a JS code (each 100 ms in m case) until the document is ready. 在准备好文档之前,保持JS代码执行的最佳方法是什么(以m为单位,每100毫秒)。

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

One the document is ready. 一个文件准备好了。 The execution should stop. 执行应该停止。

var updateInterval;
$(function(){
 updateInterval= setInterval(function() { 
   xajax_updateLoader();
}, 100);
});

$(windows).load(function(){
    clearInterval(updateInterval)
});
var interval = setInterval(function() { ... }, 100);
window.onload = function() { clearInterval(interval); }

This clears the interval on the onload event. 这将清除onload事件的时间间隔。

var handle = setInterval(function() { 
   xajax_updateLoader();
   if (jQuery.isReady) {
       //DOM is ready
       clearInterval(handle);
   }
}, 100);

Like this 像这样

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;
  }
 });
}

Use clearInterval() 使用clearInterval()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM