Search code examples
javascriptjqueryhtmldomappendchild

Add scripts dynamically in a page JavaScript


Following is my PLNKR CODE for creating dynamic script elements. But it is throwing following error -

TypeError: Argument 1 of Node.appendChild is not an object.

document.head.appendChild("script1");

I also tried document.getElementsByTagName('head')[0] for targeting but it again throw the same error.

Please let me know what I am doing wrong with the concept.

This is the answer I followed for this - Stack Link

My JS code -

(function(){

  var script1 = document.createElement('script');
  script1.src= "script1.js";
  //document.getElementsByTagName('head')[0].appendChild("script1");
  document.head.appendChild("script1");

  var add = document.createElement('script');
  add.src= "add.js";
  //document.getElementsByTagName('head')[0].appendChild("add");
  document.head.appendChild("add");

  var subtract = document.createElement('script');
  subtract.src= "subtract.js";
  //document.getElementsByTagName('head')[0].appendChild("subtract");
  document.head.appendChild("subtract");

  $("#add").find('.result').text(c);
  $("#subtract").find('.result').text(d);

})();

Solution

  • you are passing string instead of the element reference.

    Do this:

    document.head.appendChild(script1);
    

    instead of:

    document.head.appendChild("script1");