简体   繁体   中英

How to load css content as a StyleSheet object?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM