Simply including a script in the DOM does not guarantee that it has loaded, just like adding an image to the DOM doesn't mean the image is fully loaded. Loading scripts, images, or any URL content happens asynchronously, and the DOM does not wait for them to finish loading before continuing execution. In your code, you are calling a function immediately after adding the script to the page structure, but the script may not have finished loading yet.
Pure JavaScript solution:
Dynamically load external JavaScript file and wait for it to load without using jQuery
jQuery solution:
jQuery provides a helpful method called getScript:
$.getScript( "myfile.js", function( data, textStatus, jqxhr ) {
// Once the script is loaded, functions can be called here
});
It's important to note that the appendChild method adds a child element as the last child. Considering your example:
<head>
<!-- other head elements -->
<script src="example.js"></script>
<!-- other head elements -->
<!-- FILE WILL BE ADDED HERE AS THE LAST CHILD -->
<script src="myFile.js"></script>
</head>
So, myFile.js will be added last in the head section, ensuring that it is not available in scripts added before it.