0

我正在尝试制作一个 javascript 嵌入,它将在页面加载时对其进行操作。该脚本在标题中,我希望它能够在 document.querySelector 找到元素后立即对其进行操作。换句话说,它需要在 document.readyState 处于“交互”状态时,在“加载”之前对 DOM 中的变化做出反应。我不能使用超时/间隔,因为文档加载会阻塞,直到整个文档被加载,所以如果我设置 0ms 的超时,它不会执行,直到 document.readyState 被“加载”。

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

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

4

2 回答 2

0

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

于 2015-07-09T21:47:04.920 回答
0

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

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

另一个更新:

我发现这个链接可能会很有趣。它使用动画来确定对象何时被插入到 DOM 中。我用一点 POC 创建了一个小提琴,它似乎可以满足您的要求。

于 2015-07-09T21:53:58.220 回答