How to add DOM element script to head section?

I want to add DOM element to head section of HTML. jQuery does not allow adding DOM element script to the head section and they execute instead, Reference.

I want to add script tags and write a script within <head> section.

var script = '<script type="text/javascript"> //function </script>'
$('head').append(script);

Something like this with functions. I tried jQuery and javascript\, but it does not work.

Please tell me how to add and write script to head by jQuery or javascript.

I tired the javascript to add DOM element, but it does not work with .innerHTML() to write to head. I am using jQuery 2.0.3 and jQuery UI 1.10.3.

I want to add base64 encoded script to head section. I use base64 decoder js like this to decode the javascript and then put on the head section.

//Edited
It will be

$.getScript('base64.js');
var encoded = "YWxlcnQoImhpIik7DQo="; //More text
var decoded = decodeString(encoded);
var script = '<script type="text/javascript">' +decoded + '</script>';
$('head').append(script);

To fit an encoded script and the addition in one javascript file. I want to use base64.js or some other decoder javascript files for browsers does not accept atob().


try this

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'url';    

document.head.appendChild(script);

If injecting multiple script tags in the head like this with mix of local and remote script files a situation may arise where the local scripts that are dependent on external scripts (such as loading jQuery from googleapis) will have errors because the external scripts may not be loaded before the local ones are.

So something like this would have a problem: ("jQuery is not defined" in jquery.some-plugin.js).

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

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js";
head.appendChild(script);

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "/jquery.some-plugin.js";
head.appendChild(script);

Of course this situation is what the .onload() is for, but if multiple scripts are being loaded that can be cumbersome.

As a resolution to this situation, I put together this function that will keep a queue of scripts to be loaded, loading each subsequent item after the previous finishes, and returns a Promise that resolves when the script (or the last script in the queue if no parameter) is done loading.

load_script = function(src) {
    // Initialize scripts queue
    if( load_script.scripts === undefined ) {
        load_script.scripts = [];
        load_script.index = -1;
        load_script.loading = false;
        load_script.next = function() {
            if( load_script.loading ) return;

            // Load the next queue item
            load_script.loading = true;
            var item = load_script.scripts[++load_script.index];
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = item.src;
            // When complete, start next item in queue and resolve this item's promise
            script.onload = () => {
                load_script.loading = false;
                if( load_script.index < load_script.scripts.length - 1 ) load_script.next();
                item.resolve();
            };
            head.appendChild(script);
        };
    };

    // Adding a script to the queue
    if( src ) {
        // Check if already added
        for(var i=0; i < load_script.scripts.length; i++) {
            if( load_script.scripts[i].src == src ) return load_script.scripts[i].promise;
        }
        // Add to the queue
        var item = { src: src };
        item.promise = new Promise(resolve => {item.resolve = resolve;});
        load_script.scripts.push(item);
        load_script.next();
    }

    // Return the promise of the last queue item
    return load_script.scripts[ load_script.scripts.length - 1 ].promise;
};

With this adding scripts in order ensuring the previous are done before staring the next can be done like...

["https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js",
 "/jquery.some-plugin.js",
 "/dependant-on-plugin.js",
].forEach(load_script);

Or load the script and use the return Promise to do work when it's complete...

load_script("some-script.js")
.then(function() {
    /* some-script.js is done loading */
});

try out ::

var script = document.createElement("script");
script.type="text/javascript";
script.innerHTML="alert('Hi!');";
document.getElementsByTagName('head')[0].appendChild(script);

As per the author, they want to create a script in the head, not a link to a script file. Also, to avoid complications from jQuery (which provides little useful functionality in this case), vanilla javascript is likely the better option.

That may possibly be done as such:

var script = document.createTextNode("<script>alert('Hi!');</script>");   
document.getElementsByTagName('head')[0].appendChild(script);

Some clarification to those who may be confused on why this works: All code in the webpage is text. Text is the most fundamental type in a web page. The browser simply starts processing through the text, following its rules, until it reaches the end (this includes loopbacks, recursion, etc.)

For this to work, the script that makes this tag must also be in the header. The browser, when processing, will hit this code before reaching the end of the header, append the script you want onto the header, and then reach it later as it continues to process. If you had a reliable end footer, you could change out 'head' for 'footer' or similar, but considering the most reliable across sites that have scripts is the existence of the header tag, that makes it the most useful option in this case.