Is javascript appendChild not synchronous
Asked Answered
L

1

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?

Lowly answered 14/2, 2014 at 5:42 Comment(5)
It does synchronously append the script node. It does asynchronously load the script.Cerography
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.Cerography
Wrapping it inside jquery document ready may help.Nicoline
@MACMAN: No, definitely not.Cerography
Related: #3248884Ceiling
L
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.

Licensee answered 20/1, 2022 at 14:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.