How to add a DOM script element to a chapter section?

I want to add a DOM element in the head section of HTML. jQuery does not allow you to add a DOM script element to a chapter section, and instead they are executed instead of Link .

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

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

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

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

I'm tired of javascript to add a DOM element, but it does not work with .innerHTML() for writing to the head. I am using jQuery 2.0.3 and jQuery UI 1.10.3.

I want to add a base64 encoded script to the header section. I am using base64 decoder js like this to decode javascript and then put on the chapter section.

// Edited
This will

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

Install an encoded script and add javascript to one file. I want to use base64.js or some other javascript files for decoder for browsers, does not accept atob() .

+9
javascript jquery dom html
source share
10 answers

try it

 var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'url'; document.getElementsByTagName('head')[0].appendChild(script); 
+33
source share

If you embed several script tags in your head like this, using a mixture of local and remote script files, you may experience a situation where local scripts that depend on external scripts (for example, loading jQuery from googleapis) will fail because external scripts may not Loads earlier than local ones.

So something like this will 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, in this situation .onload () is used, but if multiple scripts are loaded, this can be cumbersome.

As a solution to this situation, I put together this function, which will store the script queue for loading, loading each subsequent element after the previous one is completed, and returns a promise that is resolved when the script (or the last script in the queue, if without parameters) is loaded.

 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 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 addition of scripts, to make sure that the previous is done, before proceeding to the next, you can do as ...

 ["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 download the script and use the Promise return to do the work after it's finished ...

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

try ::

 var script = document.createElement("script"); script.type="text/javascript"; script.innerHTML="alert('Hi!');"; document.getElementsByTagName('head')[0].appendChild(script); 
+4
source share
 var script = $('<script type="text/javascript">// function </script>') document.getElementsByTagName("head")[0].appendChild(script[0]) 

But in this case, the script will not be executed, and the functions will not be available in the global names folder. To use the code in <script> , you need to do as in the question

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

+2
source share

This is an old question, and I know that it asks about adding a script tag to the head, however, based on the explanation of the OPs, they really just intend to execute some JS code that was obtained through some other JS function.

This is much easier than adding a script tag to the page.

Just:

 eval(decoded); 

Eval will execute the JS string in the string, without having to add it to the DOM at all.

I do not think that it is ever really necessary to add a script tag to the DOM after loading the page.

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

+2
source share

According to the author, they want to create a script in the head, not a link to a script file.

This can be done as such:

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

The best solution I found:

 Append_To_Head('script', ' alert("hii"); '); //or Append_To_Head('script', 'http://example.com/script.js '); //or Append_To_Head('style', ' #myDiv{color:red;} '); //or Append_To_Head('style', 'http://example.com/style.css '); function Append_To_Head(elemntType, content){ // if provided content is "link" or "inline codes" var Is_Link = content.split(/\r\n|\r|\n/).length <= 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); } 
+1
source share

Here is a safe and reusable function to add a script to the header section if it does not already exist.

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> 
+1
source share

You can do:

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

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

Just add your server language from the variable. w / php something like this will go as follows.

Please note that this will only work if the script loads with page loading. If you want to download it dynamically, this solution will not help you.

Php

HTML

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

In summary: decode with serveride and put it in your HTML using the server language.

0
source share

All Articles