[英]How to execute js code after an async script has altered the dom?
我正在加载更改dom的异步脚本。 如果将onload
添加到脚本,则可以在脚本加载后运行代码。 但是,该脚本仍未编辑dom。 有没有办法等到dom编辑完成后再运行我的代码?
简单的例子:
<script>
function onLoad() {
// this logs null, but it should return a div
console.log('loaded', document.getElementById('asdf'));
}
var s = document.createElement("script");
s.type = "text\/javascript";
s.onload = onLoad
s.src = "some script that adds a div with id of asdf";
document.head.insertAdjacentElement('beforeend', s);
</script>
问题是您正在立即调用onLoad()
。 Remove ()
引用函数onLoad
,而不是调用该函数。
<div id="asdf">asdf</div> <script> function onLoad() { // this logs null, but it should return a div console.log('loaded', document.getElementById('asdf')); } var s = document.createElement("script"); s.type = "text/javascript"; s.onload = onLoad; s.src = "data:text/javascript,console.log('script src')"; document.head.insertAdjacentElement('beforeend', s); </script>
尝试添加addEventListener
以等待元素加载完毕,然后再运行脚本。
function onLoad() { document.addEventListener("load",function(e){ if(e.target.id == 'asdf'){ console.log('loaded', document.getElementById('asdf')); } }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.