Is there a way to add css from a string in the javascript file to the head of a document with javascript?
Let's say we have a webpage, which has a lightbox script, this script requires a css file to function.
Now adding this css file with <link>
will make the css file download even for people that don't have js enabled.
I know that I can dynamically load the css file with the script, but that also means that there will be 2 http requests, and in cases where there is little to no css in the file I find this inefficient.
So I thought to myself, what if you could put the css that you have in the css file, into the script, have the script parse the css and add it into the head, or even better just have the script add the css directly into the <head>
of the document.
But I have found nothing online that suggests that this is possible, so is it possible to add css to the head with js?
Edit + SOLUTION:
I edited roryf's answer to work cross browser (except IE5)
Javascript:
function addcss(css){
var head = document.getElementsByTagName('head')[0];
var s = document.createElement('style');
s.setAttribute('type', 'text/css');
if (s.styleSheet) { // IE
s.styleSheet.cssText = css;
} else { // the world
s.appendChild(document.createTextNode(css));
}
head.appendChild(s);
}
See Question&Answers more detail:os