简体   繁体   中英

Insert html between the head tags using JavaScript

In previous quests we looked at how we could insert code into a tag and with multiple attributes, and before the first tag (doctype), but what about inserting code between the head tags such as new CSS style sheets and JavaScript inserts.

I did searched here and found some related posts, but no examples that work.

For example, how to add the following lines of code using JavaScript only...

<link rel="stylesheet" type="text/css" href="chrome.css" />
<script type="text/javascript" src="chrome.js"></script>

One suggestion below looked promising, but when tested it didn't actually work, for example...

var refScript = "<SCRIPT>alert('OK');</SCRIPT>";
document.getElementsByTagName("head")[0].innerHTML += refScript;

Assuming you always actually have a <head> , you can do this:

document.getElementsByTagName("head")[0].innerHTML += "<whatever />";

You can of course also use the DOM model instead of innerHTML.

Here's how you can do that using the DOM methods.

var scrp = document.createElement('script');
scrp.type = 'text/javascript';
// approach 1:
scrp.innerHTML = "alert('OK');";
// approach 2:
var txt = document.createTextNode("console.log('hi');");
scrp.appendChild(txt);
document.head.appendChild(scrp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM