跳过JavaScript DOMContentLoaded事件

时间:2018-01-26 19:34:38

标签: javascript javascript-events domcontentloaded

我做了一个简单的测试页面:

<!DOCTYPE html> 
<html>
<head>
<script>   
//
console.log("script run"); 
//
document.addEventListener('DOMContentLoaded', function(event) {
//
alert("DOMContentLoaded event");
});
</script>
</head>
<body>
Test DOMContentLoaded
</body>
</html>

并且,有时(可能在30个请求中一次)DOMContentLoaded事件被跳过。

这可能是因为页面加载不正确。但在日志中我看到:&#34;脚本运行&#34;。我想制作一个重复的DOMContentLoaded事件函数,如果跳过DOMContentLoaded事件,我的函数就做了正确的工作。

我找到了这个解决方案:

1)

// The basic check
if(document.readyState === 'complete') {
    // good to go!
}

// Polling for the sake of my intern tests
var interval = setInterval(function() {
    if(document.readyState === 'complete') {
        clearInterval(interval);
        done();
    }    
}, 100);

2)

HTMLDocument.prototype.ready = function () {
    return new Promise(function(resolve, reject) {
        if (document.readyState === 'complete') {
            resolve(document);
        } else {
            document.addEventListener('DOMContentLoaded', function() {
            resolve(document);
        });
                    }
    });
}
document.ready().then(...);

3)

document.addEventListener('readystatechange', function docStateChange(e) {
    if(e.target.readystate === 'complete') {
        e.target.removeEventListener('readystatechange', docStateChange);
        done();
    }
});

4)

// This is needed to prevent onreadystatechange being run twice
var ready = false;

document.onreadystatechange = function() {

    if (ready) {
        return;
    }

    // interactive = DOMContentLoaded & complete = window.load
    if (document.readyState == 'interactive' || document.readyState == 'complete') {
        ready = true;

        // init you code here
    }
};

但哪种解决方案更正确?这些之间有什么区别?

1 个答案:

答案 0 :(得分:0)

为我工作:

<!DOCTYPE html>
<html>
<head>
  <script>
    // This is needed to prevent onreadystatechange being run twice
    var ready = false;

    document.onreadystatechange = function () {
      if (ready) {
        alert(document.getElementById('testing').getAttribute("class"));
        return;
      }

      // interactive = DOMContentLoaded & complete = window.load
      if (document.readyState === 'interactive' || document.readyState === 'complete') {
        ready = true;

        // init your code here
      }
    };
  </script>
</head>
<body>
Test DOMContentLoaded
<p>
  <button type='button' id='testing' class='btn border3'>a button</button>
</p>
</body>
</html>