【问题标题】:Is it possible to read the HTML body before the DOM-ready event?是否可以在 DOM-ready 事件之前读取 HTML 正文?
【发布时间】:2019-02-08 13:21:56
【问题描述】:

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

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

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

【问题讨论】:

  • explore document.addEventListener("DOMContentLoaded", ready); 其中ready 是一个要执行的函数,但 DOM 可能并未全部加载,因此 window.onload 可能是您所寻求的,因为图像将被加载
  • 尝试在加载之前读取正文以操纵加载的内容,这听起来像是一个糟糕的设计。如果您需要根据内容加载不同的脚本,那么提供该内容的服务器确实应该这样做。
  • 您始终可以从内联脚本访问 DOM,但它不会包含尚未解析的节点
  • “HTML 正文内容” - 如果它们(脚本)在头部怎么办?

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


【解决方案1】:

也许通过订阅来查看状态变化。每个的内联 cmets。

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

【讨论】:

  • 注意我同意其他人的观点,在你得到这些之前最好在服务器上完成。这里的问题有些模棱两可。
  • 感谢您的建议,尽管它对我不起作用:document.readyState == "interactive"DOMContentLoaded 在头部下载中的 sync 脚本之后触发(至少在 Chrome v68 上)。关于在服务器上执行此操作,我不能,因为我无法控制那部分(只是用这个细节更新了问题)。
  • @TomasRomero 我添加了更多选项,不确定您希望如何/想要什么,也许把这个放在您的页面上? -
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
  • 2011-05-04
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多