9

I am deploying a synchronous javascript library in a tag manager, using document.write("<script src=....

Are other methods of adding to the document considered async (for example: document.getElementsByTagName("head")[0].appendChild(script)) when compared to document.write?

d-_-b
  • 21,536
  • 40
  • 150
  • 256

1 Answers1

0

appendChild synchronously appends the element to the DOM (Document Object Model).

In your case it synchronously appends the script node, but it asynchronously loads the script, since the script is referenced by its src and hence needs to be loaded via the network. As pointed out by @Bergi.

Had your script been written as content of the script tag then it would have executed entirely synchronously.

let s = document.createElement("script");
s.text = "const myVar = 'hello world'";
document.getElementsByTagName("head")[0].appendChild(s)
console.log(myVar);

will output hello world to the console, thus proving that appendChild is entirely synchronous.

Lodewijk Bogaards
  • 19,777
  • 3
  • 28
  • 52