[javascript] 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().

This question is related to javascript jquery html dom

The answer is


Best solution I've found:

AppendToHead('script', 'alert("hii"); ');
//or
AppendToHead('script', 'http://example.com/script.js');
//or
AppendToHead('style',  '#myDiv{color:red;} ');
//or
AppendToHead('style',  'http://example.com/style.css');



function AppendToHead(elemntType, content){
    // detect whether provided content is "link" (instead of inline codes)
    var Is_Link = content.split(/\r\n|\r|\n/).length <= 1  &&  content.indexOf("//") > -1 && content.indexOf(" ")<=-1;
    if(Is_Link){
        if (elemntType=='script')    { var x=document.createElement('script');x.id=id;  x.src=content;  x.type='text/javascript'; }
        else if (elemntType=='style'){ var x=document.createElement('link');  x.id=id;  x.href=content; x.type='text/css';  x.rel = 'stylesheet'; }
    }
    else{
        var x = document.createElement(elemntType);
        if (elemntType=='script')    { x.type='text/javascript';    x.innerHTML = content;  }
        else if (elemntType=='style'){ x.type='text/css';    if (x.styleSheet){ x.styleSheet.cssText=content; } else { x.appendChild(document.createTextNode(content)); }   }
    }
    //append in head
    (document.head || document.getElementsByTagName('head')[0]).appendChild(x);
}

try this

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

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

var script = $('<script type="text/javascript">// function </script>')
document.getElementsByTagName("head")[0].appendChild(script[0])

But in that case script will not be executed and functions will be not accessible in global namespase. To use code in <script> you need do as in you question

$('head').append(script);


Here is a safe and reusable function for adding script to head section if its not already exist there.

see working example here: Example

<!DOCTYPE html>
<html>
  <head>
    <base href="/"/>
    <style>
    </style>
  </head>
  <body>
    <input type="button" id="" style='width:250px;height:50px;font-size:1.5em;' value="Add Script" onClick="addScript('myscript')"/>
    <script>
      function addScript(filename)
      {
        // house-keeping: if script is allready exist do nothing
        if(document.getElementsByTagName('head')[0].innerHTML.toString().includes(filename + ".js"))
        {
          alert("script is allready exist in head tag!")
        }
        else
        {
          // add the script
          loadScript('/',filename + ".js");
        }
      }
      function loadScript(baseurl,filename)
      {
        var node = document.createElement('script');
        node.src = baseurl + filename;
        document.getElementsByTagName('head')[0].appendChild(node);
        alert("script added");
      }
    </script>
  </body>
</html>

For modern browsers, the best solution is to use Promises.

Go to https://stackoverflow.com/a/63936671/13720928 to find out more!


This is an old question, and I know its asking specifically about adding a script tag into the head, however based on the OPs explanation they actually just intend to execute some JS code which has been obtained via some other JS function.

This is much simpler than adding a script tag into the page.

Simply:

eval(decoded);

Eval will execute a string of JS in-line, without any need to add it to the DOM at all.

I don't think there's ever really a need to add an in-line script tag to the DOM after page load.

More info here: http://www.w3schools.com/jsref/jsref_eval.asp


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);

<script type="text/JavaScript">
     var script = document.createElement('SCRIPT');
    script.src = 'YOURJAVASCRIPTURL';
    document.getElementsByTagName('HEAD')[0].appendChild(script);
 </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 */
});

I use PHP as my serverside language, so the example i will write in it - but i'm sure there is a method in your server side as well.

Just have your serverside language add it from a variable. w/ php something like that would go as follows.

Do note, that this will only work if the script is loaded with the page load. If you want to load it dynamically, this solution will not help you.

PHP

HTML

<head>
    <script type="text/javascript"> <?php echo $decodedstring ?> </script>
</head>

In Summary: Decode with serverside and put it in your HTML using the server language.


you could do:

var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.src = "script_source_here";
(document.getElementsByTagName("head")[0] || document.documentElement ).appendChild(scriptTag);

try out ::

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component