I am having a hard time dynamically loading scripts onto the DOM.
function addScript(fileName) {
document.body.innerHTML += `<script src='components/${fileName}/${fileName}.js'></script>`
}
addScript('message-interface')
This is the way I would like to add the script, as it easy to write and read. Unfortunately, although the script element is being added to the DOM, the .js file is not being loaded.
Alternatively, I have used appendChild like this . . .
function addScript() {
let script = document.createElement('script')
script.src ='components/message-interface/message-interface.js'
document.body.appendChild(script)
}
addScript()
This successfully loads my script onto the DOM.
I have checked multiple times, and the script element being loaded onto the DOM is identical with both pieces of code, only using innerHTML does not load the script into memory while append child does.
Why is it that both results yield a DOM element being added to my body tag, but only one of them allows the .js file to be loaded?!
Thank you!