Luca S.
Luca S.

Reputation: 1162

When to call document.appendChild()?

In my page I dynamically add a script with a function like this:

function addScript( src ) {
  var s = document.createElement( 'script' );
  s.setAttribute( 'src', src );
  document.body.appendChild( s );
}

I'm wondering though if I should wait for the document to be loaded before doing this. Is it possible that the body in the document may be not ready yet?

I'm using this at the moment:

document.onreadystatechange = function () {
    if (typeof document.body !== 'undefined') {
        addScript('http://my.url);
    }
};

Not sure if it is unnecessary though and maybe delay the load of the script in the page.

Upvotes: 2

Views: 646

Answers (4)

user7148391
user7148391

Reputation:

I have had the same issue tryin to add a button to the youtube page using an extension, but since the page has a load of ajax calls my button always gets overwritten.

I would suggest you use

window.addEventListener("DOMNodeInserted", function(){

}, false);

With this each time the dom get changed your code will run, and you should put some logic checks if your element is still in the document if not add it again, and so on. Hackie but it works.

Upvotes: 0

user8761909
user8761909

Reputation:

Instead of doing document.onreadystatechange I would use document.onload, which fires after the document has finished loading all elements. onreadystatechange can fire multiple times in one session (which I have utilized previously), notably after ajax loading. onload only fires once the page finishes loading, and never again.

The readystatechange event is fired when the readyState attribute of a document has changed.


The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.

Sources:
readystatechange
onload

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

onreadystatechange is used in reference to a http request. ( or used only by the older versions of IE )

The best thing you could do it call the method just below the closing of the body tag. At this point you can be sure that the document has indeed loaded.

<script>
   addScript('http://my.url');
</script>

</body>

But you can alway attach the callback to the onload event of the document.

Upvotes: 0

llama
llama

Reputation: 2537

It is possible that the body will not yet be available, but the head should be, so you could append it there.

document.head.appendChild(s);

Otherwise, if you do want to wait for the document to load, use the DOMContentLoaded event.

document.addEventListener("DOMContentLoaded", function() {
  // inject the script
});

Upvotes: 1

Related Questions