Immediately execute dynamically loaded JS script

5k Views Asked by At

at the top of the head of my document I dynamically load a script:

<script>
var script = document.createElement("script");
script.setAttribute("src", "mydomain.com/main.js");
var head = document.head;
head.insertBefore(script, head.firstChild);
</script>

Content of main.js:

console.log('test');

However, the page loads fully before it outputs test. In the network panel I can also see all the images loading before finally the script executes.

How can I make the script load and execute directly after it was inserted into the document?

2

There are 2 best solutions below

1
Divneet On

move this script tag to the head of the html. then it should assure you that the script executes before any body is rendered. Also you could add this script to the start of the body tag.

0
Andre Brdoch On

I found the solution myself. Dynamically inserted scripts are treated as async by default. Setting it to async=false fixed it:

<script>
var script = document.createElement("script");
script.setAttribute("src", "mydomain.com/main.js");
script.setAttribute("async", "false");
var head = document.head;
head.insertBefore(script, head.firstChild);
</script>