10

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?

5
  • 5
    It does synchronously append the script node. It does asynchronously load the script. Commented Feb 14, 2014 at 5:44
  • I don't think a question for the Why is on-topic here. That's just how it was implemented, and made it into the spec. Commented Feb 14, 2014 at 5:45
  • Wrapping it inside jquery document ready may help. Commented Feb 14, 2014 at 5:46
  • 4
    @MACMAN: No, definitely not. Commented Feb 14, 2014 at 8:46
  • Related: stackoverflow.com/questions/3248384/… Commented Jan 17, 2017 at 2:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.