是否可以在 Javascript 中触发文档加载事件之前响应添加到 DOM 的元素?

Is it possible to respond to elements being added to the DOM before the document load event is fired in Javascript?

我正在尝试制作一个 javascript 嵌入,它将在页面加载时对其进行操作。该脚本在 header 中,我希望它能够在 document.querySelector 找到元素后立即对其进行操作。换句话说,它需要对 DOM 的变化做出反应,而 document.readyState 是 "interactive",然后才是 "loaded"。我不能使用 timeout/interval,因为在加载完整文档之前,文档加载会阻塞,所以如果我设置 0ms 的超时,它将不会执行,直到 document.readyState 为 "loaded"。

是否有任何事件会在元素添加到 DOM 时触发?我尝试了 DOMNodeInserted,但它似乎只对加载文档后异步添加的元素触发。

最后,这必须只用 javascript 来完成;我无权访问 html 或服务器。正在嵌入其他人的网站。

也许你问错了问题?为什么不用您需要的任何 shell 或基本框架加载页面,然后使用 AngularJS 之类的东西来动态呈现您需要的内容?你不一定需要服务器来做这样的事情。

您应该将事件附加到文档本身,然后检查事件的目标,如果它是您需要的,则执行您想要的操作。 例如:

document.addEventListener("click", function(e){
  var element = e.target;
  if (element.nodeName === "A") {
    //I am gonna do something with <a> elements
    //Don't forget to return true if it is an anchor and you want the default event to trigger because if not, it will cancel the event.

  } else if (element.className.match("myClass")) {
    //OK, this element contains the class i am looking for, let's do something with it
  } else if (element.id === "myId") {
    //I finally found the element with the ID i was looking for
  }
});

更新(对于节点插入):

document.addEventListener("DOMNodeInserted", function(e){
      // e is a MutationEvent
      var element = e.target;
      //Behavior here is pretty much the same as above
      if (element.nodeName === "A") {
        //I am gonna do something with <a> elements
        //Don't forget to return true if it is an anchor and you want the default event to trigger because if not, it will cancel the event.

      } else if (element.className.match("myClass")) {
        //OK, this element contains the class i am looking for, let's do something with it
      } else if (element.id === "myId") {
        //I finally found the element with the ID i was looking for
      }
    });

另一个更新:

我发现这个 link that may result interesting. It uses animations to determine when an object has been inserted into the DOM. I created a fiddle 有一点 POC,它似乎可以满足您的要求。