Timo Huovinen Timo Huovinen - 2 years ago 155
HTML Question

Add CSS to <head> with JavaScript?

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

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
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?


I edited roryf's answer to work cross browser (except IE5)


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

Answer Source

If you don't want to rely on a javascript library, you can use document.write() to spit out the required css, wrapped in style tags, straight into the document head:

  <script type="text/javascript">
    document.write("<style>body { background-color:#000 }</style>");
  # other stuff..

This way you avoid firing an extra HTTP request.

There are other solutions that have been suggested / added / removed, but I don't see any point in overcomplicating something that already works fine cross-browser. Good luck!


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download