My guess is that since my scripts are loaded synchronously, the log outputs whatever has been loaded up to this point. How could I avoid that? I want my logging <script> to be as close to the top of the HTML as possible, while having access to all the HTML content.
What I've tried
If I put this script in the <head>:
var req = new XMLHttpRequest();
req.open("GET", document.location.href + "index.html", false);
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (req.status === 200 || req.status == 0) {
console.log(req.responseText);
}
}
}
req.send(null);
I get the desired result. But I don't like how easily it could fail. For example, if I paste this code as a snippet here in stackoverflow, it doesn't work because the requested file doesn't exist. If the document is named notindex.html, it would fail too.
Are there any alternatives or a reliable way to request the opened HTML document via an XMLHttpRequest?
Edit
I want to have access to all the HTML content before all stylesheets, scripts and images have loaded. That's the reason I want the logging script to be at the top. The XMLHttpRequest does it, but is unreliable.
解决方案
You can use the DOMContentLoaded event to run the function after your document has completely loaded: