0

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!

1 Answers1

1

Simply put, because the spec says so:

https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0

script elements inserted using innerHTML do not execute when they are inserted.

Also worth checking security considerations from https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML

juvian
  • 15,875
  • 2
  • 37
  • 38
  • I guess sometimes we must just accept our overlords rule. – Ashe Austaire Mar 07 '18 at 17:00
  • @AsheAustaire You can use `document.write` just be sure it's the very first thing that loads and don't use it any other time. – zer00ne Mar 07 '18 at 17:03
  • 1
    Why are you referencing a decade old working **draft** instead of the current spec? – Quentin Mar 07 '18 at 17:12
  • @Quentin all places I checked mentioned that working draft, and couldn´t find it on current one. Even current mozilla page points to same link. But if you find it on current spec feel free to edit link – juvian Mar 07 '18 at 17:21