Home > Enterprise >  How can I load script tags from a string?
How can I load script tags from a string?

Time:11-23

An external source is providing the content of the script tags written as HTML in a string. I need to add these script tags into the head. If I do it like this, all script tags are added to the DOM in head tag, however none of the sources are actually being loaded (devtools network tab).

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <script>
        let sLoadThis = '<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/underscore@latest/underscore-umd-min.js">'
        sLoadThis = sLoadThis   "<"   "/script>"
        let oScript = $(sLoadThis).get(0);
        document.head.appendChild(oScript);
    </script>
  </body>
</html>

If I sort of use the jQuery as an interpreter to then insert the script tag with vanilla JS, it works:


<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <script>
        let sLoadThis = '<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/underscore@latest/underscore-umd-min.js">'
        sLoadThis = sLoadThis   "<"   "/script>"
        let oScript = $(sLoadThis).get(0);
        var vanillaScript = document.createElement('script')
        vanillaScript .type = 'text/javascript'
        vanillaScript .src = oScript.src
        document.head.appendChild(vanillaScript )
    </script>
  </body>
</html>

I would like to understand why it doesn't work in my first example.

CodePudding user response:

The second example runs because you 're using a dom node. That 's how appendChild() works. The jQuery get() method works with existing dom elements. The only thing you 've got is a string, that does not exist in your dom yet. Try the following.

let script = $.parseHtml(sLoadThis);
console.log(script.get(0)); // should be a script dom node element

document.head.appendChild(script.get(0));

In vanilla JavaScript its even easier and much more faster than jQuery because you don 't have to use a dependency.

const fragment = document.createRange().createContextualFragment(htmlStr);
document.head.appendChild(fragment);
  • Related