Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert a script into HTML head dynamically using JavaScript? [duplicate]

How can I insert a script into HTML head dynamically using JavaScript?

like image 828
Wasim A. Avatar asked Feb 27 '11 09:02

Wasim A.


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 we add two scripts in HTML?

You can have as many <SCRIPT></SCRIPT> tags as you would like in a document. The <SCRIPT> tags are processed as they are encountered.


2 Answers

var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.onload = function() {     callFunctionFromScript(); } script.src = 'path/to/your-script.js'; head.appendChild(script); 
like image 145
Bugs Bunny Avatar answered Sep 21 '22 22:09

Bugs Bunny


Here is how I injected a function on the fly without any source file, etc.

document.head.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' ); 

And to inject to body

document.body.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' ); 

After executing this, if you try LogIt('hello');, you should see 'hello' in the console.

like image 40
Rajnikant Avatar answered Sep 20 '22 22:09

Rajnikant