I’m trying to understand why this code doesn’t work and the alert output is just blank.
<script type="text/javascript">
(function() {
...
var s = document.getElementsByTagName('script')[0]; alert(s.innerHTML);
s.parentNode.insertBefore(res, s);
...
})();
</script>
It should add res before s if I’m not wrong. That’s what I specifically need, as I tried to append it to body and it’s added successfully (after doing that though I have to run some code inside this function, so if the script is not loaded before it, such code will error).
This function should run when document is loaded or is that the problem? In particular, the getElementsByTagName function seems to not return anything.
Thanks to everyone.
You cannot run this type of code before the document is loaded. This code has to be loaded before it can be run (see the circular argument here). And, by then, much of the rest of the document has been loaded. You can dynamically load scripts AFTER the document has been loaded. If you need a script loaded before other scripts, then you either have to put them all in the document statically in the order you need them to be run or you need to add them all dynamically in the order you need them to run and you will need to keep track of completion of one load before loading the next.
If you care to describe the broader problem you’re trying to solve, we can probably suggest a more elegant solution than what you are pursuing.