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?
move this
scripttag 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 thebodytag.