有什么方法可以使用 document.createElement() 跟踪元素的创建吗?

eaw*_*wer 5 javascript dom dom-events mutation-observers

有什么办法可以赶上document.createElement()活动吗?

例如,在<body>我的部分内的某个地方

<script>
    var div = document.createElement("div");
<script>
Run Code Online (Sandbox Code Playgroud)

是否可以从该<head>部分跟踪该事件(使用某些 addEventListener、突变观察器或任何其他方式)?

注意:我需要跟踪元素的创建,而不是插入

Jer*_*her 5

警告此代码不适用于所有浏览器。当涉及到 IE 时,所有的赌注都将落空。

(function() {
  // Step1: Save a reference to old createElement so we can call it later.
  var oldCreate = document.createElement;

  // Step 2: Create a new function that intercepts the createElement call
  // and logs it.  You can do whatever else you need to do.
  var create = function(type) {
    console.log("Creating: " + type);
    return oldCreate.call(document, type);
  }

  // Step 3: Replace document.createElement with our custom call.
  document.createElement = create;

}());
Run Code Online (Sandbox Code Playgroud)