0

I made a simple page for testing:

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

And, sometimes (maybe once in 30 requests) DOMContentLoaded event is skipped.

Perhaps this is due to incorrect loading of the page. But in log I see: "script run". I want make a duplicate DOMContentLoaded event function, and if DOMContentLoaded event is skipped, my function did the right job.

I found this solutions:

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

But which of the solutions is more correct? And what is the difference between these?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Reads
  • 9
  • 1

1 Answers1

0

Worked for me:

<!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>