如何在运行脚本之前检查元素是否已加载到页面上? [英] How to check if an element has been loaded on a page before running a script?
问题描述
所以我在我的公司模板中创建我的页面,它只允许我们访问页面的正文.我们无权访问 head 标记,并且在页面的下部加载了我们无权访问的脚本.其中一个脚本将元素动态加载到页面上.我需要在该元素上运行另一个脚本,但是因为该元素直到我的脚本已经运行后才会加载到页面上,所以我无法访问该元素.有没有办法在运行我的脚本之前检查该元素是否已加载到页面上?
So I am creating my page in my companies template, which only allow us access to the body of the page. We don't have access to the head tag and there are scripts loaded on a lower part of the page that we don't have access to. One of these scripts dynamically loads an element onto the page. I need to run another script on that element, but because the element isn't loaded on the page until after my script has already ran I can't access that element. Is there a way I can check to see if that element has already been loaded on the page before running my script?
如果我需要更好地解释,请告诉我.
Let me know if I need to explain better.
<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>
推荐答案
听起来像是 MutationObserver
!
Sounds like a job for MutationObserver
!
MutationObserver
就像一个事件监听器:你可以将它附加到任何 DOM 元素来监听变化:
A MutationObserver
is like an event listener: you can attach it to any DOM element to listen for changes:
var observer = new MutationObserver(function (mutationRecords) {
console.log("change detected");
});
回调被传递一个 MutationRecord
的数组,这些数组包含不同的添加/删除/修改节点列表.
The callback is passed an array of MutationRecord
s, which hold different lists of added/deleted/modified nodes.
然后,我们将观察者附加到任何节点:
Then, we attach the observer to any node:
observer.observe(document.body, {childList: true});
// second argument is a config: in this case, only fire the callback when nodes are added or removed
注意:IE 支持并不惊人.(惊喜,惊喜)仅适用于 IE 11.(不过,Edge 支持它.)
Note: IE support is not amazing. (surprise, surprise) Only works on IE 11. (Edge supports it, though.)
这是关于检测 DOM 更改的另一个 SO 问题:检测 DOM 中的更改
Here's another SO question about detecting changes to the DOM: Detect changes in the 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});
<button>Click</button>
<div></div>
这篇关于如何在运行脚本之前检查元素是否已加载到页面上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!