Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inject js to head (with full-code in script)

I want to add a script to the head of a site so the the head of the target html looks like so <head><script type="text/javascript">*some code...*</script></head>.


With this script works that perfect:

var head = document.getElementsByTagName('head')[0],
    script = document.createElement('script');

script.src = 'http://www.example.com/example.js';    
head.appendChild(script);

But i don't want to use any link in source.

So i'm tried to add some code like this:

    function addJS(jsCode) {
    var styleElement = document.createElement('script');

    styleElement.type = 'text/javascript';

       (scriptElement.javascript) {
        scriptElement.javascript.jsText = jsCode
        scriptElement.appendChild(document.createTextNode(jsCode))

    document.getElementsByTagName('head')[0].appendChild(scriptElement);
}

var jsCode = '';
jsCode += 'code';
jsCode += 'some more code';

But I've failed. That script is not working.

How can I add a Element to the head of any html site like this? Would be great if someone could help me.

like image 979
mmmh Avatar asked Nov 26 '12 21:11

mmmh


People also ask

How do you put JavaScript in head?

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.

Should I put js script in head or body?

The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.

Can we write script in head tag?

Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.


1 Answers

Just tried this and it seemed to work. Try

function addJS(jsCode) {
    var s = document.createElement('script');

    s.type = 'text/javascript';
    s.innerText = jsCode;
    document.getElementsByTagName('head')[0].appendChild(s);
}

Demo here

like image 54
Bruno Avatar answered Oct 08 '22 15:10

Bruno