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.
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.
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.
Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With