Dynamically add script tag with src that may include document.write

324,466

Solution 1

var my_awesome_script = document.createElement('script');

my_awesome_script.setAttribute('src','http://example.com/site.js');

document.head.appendChild(my_awesome_script);

Solution 2

You can use the document.createElement() function like this:

function addScript( src ) {
  var s = document.createElement( 'script' );
  s.setAttribute( 'src', src );
  document.body.appendChild( s );
}

Solution 3

There is the onload function, that could be called when the script has loaded successfully:

function addScript( src, callback ) {
  var s = document.createElement( 'script' );
  s.setAttribute( 'src', src );
  s.onload=callback;
  document.body.appendChild( s );
}

Solution 4

a nice little script I wrote to load multiple scripts:

function scriptLoader(scripts, callback) {

    var count = scripts.length;

    function urlCallback(url) {
        return function () {
            console.log(url + ' was loaded (' + --count + ' more scripts remaining).');
            if (count < 1) {
                callback();
            }
        };
    }

    function loadScript(url) {
        var s = document.createElement('script');
        s.setAttribute('src', url);
        s.onload = urlCallback(url);
        document.head.appendChild(s);
    }

    for (var script of scripts) {
        loadScript(script);
    }
};

usage:

scriptLoader(['a.js','b.js'], function() {
    // use code from a.js or b.js
});

Solution 5

You can try following code snippet.

function addScript(attribute, text, callback) {
    var s = document.createElement('script');
    for (var attr in attribute) {
        s.setAttribute(attr, attribute[attr] ? attribute[attr] : null)
    }
    s.innerHTML = text;
    s.onload = callback;
    document.body.appendChild(s);
}

addScript({
    src: 'https://www.google.com',
    type: 'text/javascript',
    async: null
}, '<div>innerHTML</div>', function(){});
Share:
324,466

Related videos on Youtube

Cadell Christo
Author by

Cadell Christo

Updated on July 21, 2022

Comments

  • Cadell Christo
    Cadell Christo almost 2 years

    I want to dynamically include a script tag in a webpage however I have no control of it's src so src="source.js" may look like this.

    document.write('<script type="text/javascript">')
    document.write('alert("hello world")')
    document.write('</script>')
    document.write('<p>goodbye world</p>')
    

    Now ordinarily putting

    <script type="text/javascript" src="source.js"></script>
    

    In the head works fine but is there any other way I can add source.js dynamically using something like innerHTML?

    jsfiddle of what i've tried

  • EliSherer
    EliSherer almost 8 years
    Sorry... just found a better one that allow dependencies stackoverflow.com/a/1867135/678780
  • UKDataGeek
    UKDataGeek over 7 years
    How would you make this async?
  • axlotl
    axlotl about 7 years
    @mobile bloke: s.async = true;
  • brandito
    brandito over 6 years
    s.setAttribute( 'src', src ); could be s.src = src (i think?) i know this isn't pcg
  • mix3d
    mix3d about 6 years
    Learned something new. Nice!
  • user1063287
    user1063287 almost 5 years
    fyi, link not working, i couldn't find the article elsewhere.
  • Gel
    Gel over 3 years
    whats target ?
  • Malay
    Malay over 3 years
    @Gel, updated the answer, the target is document.body in most cases.
  • Admin
    Admin over 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
  • Charles Forster
    Charles Forster almost 2 years
    Thank you, you just saved me a few more hours searching for this solution