Daniel
Daniel

Reputation: 303

How to execute js code after an async script has altered the dom?

I'm loading an async script that alters the dom. If I add an onload to the script, I can run code after the script has been loaded. However, the dom has still not been edited by the script. Is there a way to wait until the dom edits have been completed before running my code?

Simple Example:

<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>

Upvotes: 0

Views: 233

Answers (2)

guest271314
guest271314

Reputation: 1

The issue is that you are calling onLoad() immediately. Remove () to reference function onLoad, instead of calling the function.

<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>

Upvotes: 1

JJJ
JJJ

Reputation: 3332

Try adding addEventListener to wait until the element has loaded and then have it run the script.

 function onLoad() {
    document.addEventListener("load",function(e){
    	if(e.target.id == 'asdf'){
    		console.log('loaded', document.getElementById('asdf'));
        }
     });
  }

Upvotes: 0

Related Questions