Create a temporary element (e. g. DIV
), assign your HTML code to its innerHTML
property, and then append its child nodes to the HEAD
element one by one. For example, like this:
var temp = document.createElement('div');
temp.innerHTML = '<link rel="stylesheet" href="example.css" />'
+ '<script src="foobar.js"><\/script> ';
var head = document.head;
while (temp.firstChild) {
head.appendChild(temp.firstChild);
}
Compared with rewriting entire HEAD
contents via its innerHTML
, this wouldn’t affect existing child elements of the HEAD
element in any way.
Note that scripts inserted this way are apparently not executed automatically, while styles are applied successfully. So if you need scripts to be executed, you should load JS files using Ajax and then execute their contents using eval()
.