如何在运行脚本之前检查页面上是否已加载元素?

use*_*567 12 html javascript jquery

所以我在我的公司模板中创建我的页面,这只允许我们访问页面正文.我们无法访问head标记,并且在页面的下半部分加载了我们无权访问的脚本.其中一个脚本动态地将元素加载到页面上.我需要在该元素上运行另一个脚本,但因为直到我的脚本已经运行之后才在页面上加载该元素,所以我无法访问该元素.有没有办法在运行脚本之前检查是否已在页面上加载该元素?

如果我需要更好地解释,请告诉我.

<head>Don't have access</head>


<body>
   <!--Needs to manipulate the element created by the companyScript.js--> 
   <script src="myScript.js"></script>

   <!--Script that runs after mine, which I don't have access too-->
   <script src="companyScript.js">
       /*Dynamically adds <div class="element"></div> to page*/
   </script>
</body>
Run Code Online (Sandbox Code Playgroud)

Hat*_*het 14

听起来像个工作MutationObserver!

A MutationObserver就像一个事件监听器:您可以将它附加到任何DOM元素以监听更改:

var observer = new MutationObserver(function (mutationRecords) {
    console.log("change detected");
});
Run Code Online (Sandbox Code Playgroud)

回调传递一个MutationRecords 数组,它包含添加/删除/修改节点的不同列表.

然后,我们将观察者附加到任何节点:

observer.observe(document.body, {childList: true});
// second argument is a config: in this case, only fire the callback when nodes are added or removed
Run Code Online (Sandbox Code Playgroud)

注意:IE支持并不令人惊讶.(惊喜,惊喜)仅适用于IE 11.(Edge支持它.)

这是关于检测DOM更改的另一个问题:检测DOM中的更改

片段:

document.querySelector("button").addEventListener("click", function () {
  document.body.appendChild(document.createElement("span"));
});

var observer = new MutationObserver(function (m) {
  if (m[0].addedNodes[0].nodeName === "SPAN")
    document.querySelector("div").innerHTML += "Change Detected<br>";
});

observer.observe(document.body, {childList: true});
Run Code Online (Sandbox Code Playgroud)
<button>Click</button>
<div></div>
Run Code Online (Sandbox Code Playgroud)


I w*_*ce. 6

这将检查该元素是否每秒存在10x,并且一旦存在,它将立即执行您的代码。

function waitForElement(id, callback){
    var poops = setInterval(function(){
        if(document.getElementById(id)){
            clearInterval(poops);
            callback();
        }
    }, 100);
}

waitForElement("idOfElementToWaitFor", function(){
    alert("element is loaded.. do stuff");
});
Run Code Online (Sandbox Code Playgroud)