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

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

This question is related to javascript src document.write

The answer is


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

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

document.head.appendChild(my_awesome_script);

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
});

A one-liner (no essential difference to the answers above though):

document.body.appendChild(document.createElement('script')).src = 'source.js';

I tried it by recursively appending each script

Note If your scripts are dependent one after other, then position will need to be in sync.

Major Dependency should be in last in array so that initial scripts can use it

_x000D_
_x000D_
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']_x000D_
let count = 0_x000D_
_x000D_
  _x000D_
 const recursivelyAddScript = (script, cb) => {_x000D_
  const el = document.createElement('script')_x000D_
  el.src = script_x000D_
  if(count < scripts.length) {_x000D_
    count ++_x000D_
    el.onload = recursivelyAddScript(scripts[count])_x000D_
    document.body.appendChild(el)_x000D_
  } else {_x000D_
    console.log('All script loaded')_x000D_
    return_x000D_
  }_x000D_
}_x000D_
 _x000D_
  recursivelyAddScript(scripts[count])
_x000D_
_x000D_
_x000D_


When scripts are loaded asynchronously they cannot call document.write. The calls will simply be ignored and a warning will be written to the console.

You can use the following code to load the script dynamically:

var scriptElm = document.createElement('script');
scriptElm.src = 'source.js';
document.body.appendChild(scriptElm);

This approach works well only when your source belongs to a separate file.

But if you have source code as inline functions which you want to load dynamically and want to add other attributes to the script tag, e.g. class, type, etc., then the following snippet would help you:

var scriptElm = document.createElement('script');
scriptElm.setAttribute('class', 'class-name');
var inlineCode = document.createTextNode('alert("hello world")');
scriptElm.appendChild(inlineCode); 
document.body.appendChild(scriptElm);

the only way to do this is to replace document.write with your own function which will append elements to the bottom of your page. It is pretty straight forward with jQuery:

document.write = function(htmlToWrite) {
  $(htmlToWrite).appendTo('body');
}

If you have html coming to document.write in chunks like the question example you'll need to buffer the htmlToWrite segments. Maybe something like this:

document.write = (function() {
  var buffer = "";
  var timer;
  return function(htmlPieceToWrite) {
    buffer += htmlPieceToWrite;
    clearTimeout(timer);
    timer = setTimeout(function() {
      $(buffer).appendTo('body');
      buffer = "";
    }, 0)
  }
})()

Here is a minified snippet, same code as Google Analytics and Facebook Pixel uses:

!function(e,s,t){(t=e.createElement(s)).async=!0,t.src="https://example.com/foo.js",(e=e.getElementsByTagName(s)[0]).parentNode.insertBefore(t,e)}(document,"script");

Replace https://example.com/foo.js with your script path.


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(){});

This Is Work For Me.

You Can Check It.

_x000D_
_x000D_
var script_tag = document.createElement('script');_x000D_
script_tag.setAttribute('src','https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js');_x000D_
document.head.appendChild(script_tag);_x000D_
window.onload = function() {_x000D_
    if (window.jQuery) {  _x000D_
        // jQuery is loaded  _x000D_
        alert("ADD SCRIPT TAG ON HEAD!");_x000D_
    } else {_x000D_
        // jQuery is not loaded_x000D_
        alert("DOESN'T ADD SCRIPT TAG ON HEAD");_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_


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 );
}

Well, there are multiple ways you can include dynamic javascript, I use this one for many of the projects.

var script = document.createElement("script")
script.type = "text/javascript";
//Chrome,Firefox, Opera, Safari 3+
script.onload = function(){
console.log("Script is loaded");
};
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);

You can call create a universal function which can help you to load as many javascript files as needed. There is a full tutorial about this here.

Inserting Dynamic Javascript the right way


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 );
}

Loads scripts that depends on one another with the right order.

Based on Satyam Pathak response, but fixed the onload. It was triggered before the script actually loaded.

_x000D_
_x000D_
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']_x000D_
let count = 0_x000D_
_x000D_
  _x000D_
 const recursivelyAddScript = (script, cb) => {_x000D_
  const el = document.createElement('script')_x000D_
  el.src = script_x000D_
  if(count < scripts.length) {_x000D_
    count ++_x000D_
    el.onload = () => recursivelyAddScript(scripts[count])_x000D_
    document.body.appendChild(el)_x000D_
  } else {_x000D_
    console.log('All script loaded')_x000D_
    return_x000D_
  }_x000D_
}_x000D_
 _x000D_
  recursivelyAddScript(scripts[count])
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to src

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this? Angular 4 img src is not found Rotate an image in image source in html html script src="" triggering redirection with button What is the right way to write my script 'src' url for a local development environment? How to properly reference local resources in HTML? Dynamically add script tag with src that may include document.write Programmatically change the src of an img tag Get img src with PHP Javascript : get <img> src and set as variable?

Examples related to document.write

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it? Execute write on doc: It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. Dynamically add script tag with src that may include document.write What are alternatives to document.write? What is the correct way to write HTML using Javascript?