title: Add CSS to <head> with JavaScript?
body: <p>Is there a way to add css from a string in the javascript file to the head of a document with javascript?</p>
  
  <p>Let's say we have a webpage, which has a lightbox script, this script requires a css file to function. </p>
  
  <p>Now adding this css file with <code>&lt;link&gt;</code> will make the css file download even for people that don't have js enabled. </p>
  
  <p>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. </p>
  
  <p>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 <code>&lt;head&gt;</code> of the document. </p>
  
  <p>But I have found nothing online that suggests that this is possible, so is it possible to add css to the head with js?</p>
  
  <h2>Edit + SOLUTION:</h2>
  
  <p>I edited roryf's answer to work cross browser (except IE5)</p>
  
  <p>Javascript:</p>
  
  <pre><code> 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);
   }
  </code></pre>