0

I have a css content with xhr load as the following code,

var xhr = new XMLHttpRequest();
xhr.open('GET', 'my.css');
xhr.onreadystatechange = function () {
    if (this.readyState == this.DONE) {
        xhr.onreadystatechange = null;
        var style = $('<style/>').html(this.responseText);

        // it will print a dom string in dev console.
        console.log(style[0]);
    }
};
xhr.send();

So far I only know how to load the css content via ajax, but I want to let the css content become a StyleSheet object, just like to access the document.styleSheets[n], I can't find any methods to do this, is there a way to do this?

my question is not apply or insert the css rules to the document, my question is how to let the css content string become a StyleSheet object, https://developer.mozilla.org/en-US/docs/Web/API/StyleSheet

Jasper
  • 2,314
  • 3
  • 26
  • 33
  • 1
    Possible duplicate of [Dynamically add css to page via javascript](http://stackoverflow.com/questions/4847313/dynamically-add-css-to-page-via-javascript) – Jorg Mar 06 '17 at 06:40
  • I dont think so, that is not my issue. – Jasper Mar 06 '17 at 06:43
  • @Jasper using `XMLHttpRequest` you load the content of `my.css` as text. You need to create an empty style-sheet and set the `cssText` as described in the duplicate, so why do you think that this won't solve you issue? An additional note: If you load style-sheets that way you either need to make sure that you do not reference other resources like images in the css rules, or that the paths are absolute. – t.niese Mar 06 '17 at 06:59

1 Answers1

1

I think you can do it as following:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'my.css');
xhr.onreadystatechange = function () {
  if (this.readyState == 4 && this.status == 200) { //4=this.DONE

    xhr.onreadystatechange = null;

    //var style = $('<style/>').html(this.responseText);
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = this.responseText;
    document.getElementsByTagName('head')[0].appendChild(style);

    var cssSheet = style.sheet; //this is the StyleSheet object you need
    var rule = cssSheet.cssRules[0]; //first rule defined in my.css
    alert("first css rule: "+ rule.selectorText + " => " + rule.style.cssText); 
  }
};
xhr.send();

The main tip is to use the sheet property of the HTMLStyleElement. it must be accessed only after you have append it to the document.

S.Serpooshan
  • 7,608
  • 4
  • 33
  • 61