是否可以在DOM-ready事件之前读取HTML正文?

时间:2018-09-03 13:15:16

标签: javascript html loading web-frontend web-performance

我需要尽快读取HTML正文内容(以DOM或原始字符串的形式),以优化一些其他脚本的加载(如果内容为X,则加载脚本A或B)如果内容为Y)。是否可以避免等待所有sync脚本加载(这是DOM就绪的条件)才能读取正文?

注意:不能将脚本更改为async

更新:我不控制服务器,因此无法在那里进行优化。

1 个答案:

答案 0 :(得分:1)

也许通过订阅来查看状态变化。内嵌评论。

// self envoking
(function() {
  console.log("self envoking in script");
}());
console.log(document.readyState); // logs "loading" first
window.onload = function() {
  console.log('onload'); // I fire later
}
document.addEventListener("DOMContentLoaded", function() {
  console.log('DOMContentLoaded');
});
document.addEventListener('readystatechange', function() {
  if (document.readyState == "loading") {
    //document is loading, does not fire here since no change from "loading" to "loading"
  }
  if (document.readyState == "interactive") {
    //document fully read. fires before DOMContentLoaded
  }
  if (document.readyState == "complete") {
    //document fully read and all resources (like images) loaded. fires after DOMContentLoaded
  }
  console.log(document.readyState)
});
<script id="myscript">
  // self envoking
  (function() {
    console.log("self envoking with id");
    window.customevent = new Event('customload');

    // Listen for the event.
    document.addEventListener('customload', function(e) {
      console.log("customload fired");  
    }, false);
    // another way
    var scriptNode = document.createElement('script');
    scriptNode.innerHTML = 'console.log("happy happy day inject");';
    document.head.appendChild(scriptNode);
  }());
</script>
<script id="another">
  var thisScriptElement = document.getElementById("another");
  // self envoking
  (function() {
    console.log("Another self envoking with id");
    // Dispatch the event.
    document.dispatchEvent(customevent);
  }());
</script>