Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using document.head.appendChild() to append a script tag that has an SRC attribute?

Tags:

javascript

Any reason why the following code isn't working?

alert("1");
document.head.appendChild("<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>");
alert("2");

(I know it is breaking because the 1 is alerted but not the 2.)

What is the proper way to accomplish the same thing? Namely, to append a script tag to the document head, where the tag gets a .js file using the SRC attribute. I don't want it to write javascript inline.

Thanks!

like image 787
Joey Avatar asked Mar 05 '14 23:03

Joey


People also ask

How do you append a script tag to head?

type = "text/javascript"; s. src = "http://somedomain.com/somescript"; $("head"). append(s); Note that the script will load and you can access the variables inside it, but you wouldn't see the actual <script> tag in the DOM.

What is the difference between appendChild and append?

append() can append several nodes and strings, whereas Node. appendChild() can only append one node.

What is inserting elements into document head?

The appendChild() method appends this created element to the head of the document.

How do I add a script to a script?

The <script> Tag In HTML, JavaScript code is inserted between <script> and </script> tags.


2 Answers

element.appendChild expects a node not a string. You should first create the node and set the attributes and then append it.

element.appendChild Reference

var sc = document.createElement("script");
sc.setAttribute("src", "https://getfirebug.com/firebug-lite.js");
sc.setAttribute("type", "text/javascript");
document.head.appendChild(sc);

For older browsers (IE < 9 etc.) that doesn't support document.head

document.getElementsByTagName("head")[0].appendChild(sc);
like image 63
Mathias Avatar answered Sep 21 '22 22:09

Mathias


This will do what the original poster wants without creating a new object.

document.head.innerHTML += "<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>";

The script will be appended to the end of the existing head section which may not be what you want.

Believe it or not this will put your script at the start of the head section without erasing the existing head section:

document.head.innerHTML = "<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>" + document.head.innerHTML;
like image 27
user14218683 Avatar answered Sep 21 '22 22:09

user14218683