Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add dynamic javascript to the head tag from a string, not a file?

Tags:

javascript

I am using Javascript to generate additional custom javascript and then adding it to the HEAD tag. The code below works great adding a javascript file, but what if the script is in a variable just generated?

var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");
scriptTag.setAttribute("src", "myfile.js");
document.getElementsByTagName("head")[0].appendChild(scriptTag);

Thank you for your attention.

like image 202
Vincent James Avatar asked Nov 14 '12 21:11

Vincent James


People also ask

How do you add a script to a head tag?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can JavaScript be added in head only?

It can go in the head or body tag. Just keep in mind that it will execute whenever is read and not necessarily when the document is finished loading.

Is it possible to dynamically load external JavaScript files in JavaScript?

To load an external Javascript file dynamically, we can create a <script> tag and insert it into the head section. var js = document. createElement("script"); js.


2 Answers

   // script text
var txt = "alert('foo');";

var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");

   // append it in a text node
scriptTag.appendChild(document.createTextNode(txt));
document.getElementsByTagName("head")[0].appendChild(scriptTag);

FWIW, you don't need a script tag for this. You can use the Function constructor instead.

var txt = "alert('foo');";

Function(txt)();
like image 174
I Hate Lazy Avatar answered Oct 14 '22 05:10

I Hate Lazy


var scriptTag = document.createElement("script");
scriptTag.setAttribute("type", "text/javascript");

scriptTag.innerHTML = "What you want here";///....

document.getElementsByTagName("head")[0].appendChild(scriptTag);

Live DEMO

like image 42
gdoron is supporting Monica Avatar answered Oct 14 '22 03:10

gdoron is supporting Monica