title: Make a createStyleSheet function with javascript( The ultimate solution? )
body: <p>I read <a href="https://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript/524798#524798">this link</a> where Cristoph make a function to add a style sheet. I think it's a brilliant idea but doesn't work properly. Example:</p>
  
  <pre><code>if(typeof document.createStyleSheet === 'undefined') {
      document.createStyleSheet = (function() {
          function createStyleSheet(href) {
              if(typeof href !== 'undefined') {
                  var element = document.createElement('link');
                  element.type = 'text/css';
                  element.rel = 'stylesheet';
                  element.href = href;
              }
              else {
                  var element = document.createElement('style');
                  element.type = 'text/css';
              }
  
              document.getElementsByTagName('head')[0].appendChild(element);
              var sheet = document.styleSheets[document.styleSheets.length - 1];
  
              if(typeof sheet.addRule === 'undefined')
                  sheet.addRule = addRule;
  
              if(typeof sheet.removeRule === 'undefined')
                  sheet.removeRule = sheet.deleteRule;
  
              return sheet;
          }
  
          function addRule(selectorText, cssText, index) {
              if(typeof index === 'undefined')
                  index = this.cssRules.length;
  
              this.insertRule(selectorText + ' {' + cssText + '}', index);
          }
  
          return createStyleSheet;
      })();
  }
  
  document.createStyleSheet( 'css/test.css' );
  var sheet = document.createStyleSheet();
  sheet.addRule('h1', 'background: red;');
  console.log( sheet );
  </code></pre>
  
  <p>When I add external file and, then, add style sheet without name, the function doesn't work properly at least in chrome. In sheet variable is stored a default style sheet of chrome:</p>
  
  <pre><code>CSSStyleSheet {rules: CSSRuleList, cssRules: CSSRuleList, ownerRule: null, media: MediaList, title: null…}
  cssRules: CSSRuleList
  0: CSSStyleRule
  1: CSSStyleRule
  2: CSSStyleRule
  3: CSSStyleRule
  ...
  627: CSSStyleRule
  628: CSSStyleRule
  length: 629
  __proto__: CSSRuleList
  disabled: false
  href: null
  media: MediaList
  ownerNode: style
  ownerRule: null
  parentStyleSheet: null
  rules: CSSRuleList
  title: null
  type: "text/css"
  __proto__: CSSStyleSheet
  </code></pre>
  
  <p>I don't know why this problem occurs. Does anyone know it?</p>
  
  <p>Edit.: to clarify a concept of source code.</p>
  
  <p>Thanks!</p>