I'm a bit confused on what's required to dynamically load a JS file into the DOM.
When I include in my HTML file, example.js will run normally.
When I include it will add to the DOM but not run it.
I previously believed that I had to recreate , then append() it to the tag. I feel as if I am missing a crucial step, I just don't know what that step is.
example.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="example.js"></script><!-- working -->
<script src="add-example-dynamically.js"></script><!-- not working -->
</head>
<body>
<script>
execute( anyScriptElement ); // not working
</script>
</body>
</html>
</body>
</html>
add-example-dynamically.js
function toExecutable( tagElement ){
// Duplicate the provided tag as a new element in order for all tags to run the 'src' attribute after adding it to the DOM
// Required to run: <script src=""></script>
var newTag = document.createElement( tagElement.tagName );
if( tagElement.hasAttributes() ){
// Check if the tag has attributes
for( var countAttributes = 0; countAttributes < tagElement.attributes.length; ++countAttributes ){
var name = tagElement.attributes[ countAttributes ].name;
var value = tagElement.attributes[ countAttributes ].value;
newTag.setAttribute( name, value );
}
}
if( tagElement.textContent ){
// Check if the tag has content within it
newTag.textContent = tagElement.textContent;
}
return newTag;
}
function execute( anyScriptElement ){
var tag = toExecutable( anyScriptElement );
document.getElementsByTagName( 'head' )[ 0 ].append( tag );
}
var theScript = document.createElement( 'script' );
theScript.src = 'example.js';
execute( theScript ); // not working
Things I've tried (or a variation of)
error loading javascript files dynamically
I've also been adding .onload and .onreadystatechange to various objects without success.
Things I don't quite yet understand
Dynamically load a JavaScript file
How do you import multiple javascript files in HTML index file without the bloat?
Dynamically load a JavaScript file
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://humanwhocodes.com/blog/2009/07/28/the-best-way-to-load-external-javascript/
Things I don't think solve my problem
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
https://gomakethings.com/a-better-way-to-load-scripts-with-javascript-or-why-document-write-sucks/
Thoughts
I have a feeling that the right solution doesn't involve XMLHttpRequest or Promises but I'm not certain.
My repository in question: Widgets
If someone could point me in the right direction, that would help me figure out what I need to look into.
FYI
Native JS ideal, not interested in JQuery.
I only care about support for Chrome, Firefox, Opera, Safari (desktop / mobile)