Insert Styles with javascript

function addCSS(cssText){
    var style = document.createElement('style'),  //Create a style element
        head = document.head || document.getElementsByTagName('head')[0]; //Get the head element
    style.type = 'text/css'; //Here you must show that the type attribute of the style element is text/css, otherwise it will not work in ie.
    if(style.styleSheet){ //IE
        var func = function(){
            try{ //Prevent stylesheet from exceeding the limit in IE
                style.styleSheet.cssText = cssText;
            }catch(e){

            }
        }
        //If the current styleSheet is not available, put it in asynchrony
        if(style.styleSheet.disabled){
            setTimeout(func,10);
        }else{
            func();
        }
    }else{ //w3c
        //In w3c browser, just create a text node and insert it into the style element
        var textNode = document.createTextNode(cssText);
        style.appendChild(textNode);
    }
    head.appendChild(style); //Insert the created style element into the head    
}

//Use
addCSS('#demo{ height: 30px; background:#f00;}');

  

Of course, this is only a basic demonstration method, which needs to be improved in practical application, such as inserting each generated css code into a style element, so that there will be no stylesheet number exceeding the limit in IE.

Encapsulation:

var importStyle=function importStyle(b){
    var a=document.createElement("style");
    var c=document;c.getElementsByTagName("head")[0].appendChild(a);
    if(a.styleSheet){
        a.styleSheet.cssText=b
    }else{
        a.appendChild(c.createTextNode(b))
    }
};
importStyle('h1 { background: red; }');//call    

seajs encapsulation

seajs.importStyle=function importStyle(b){
    var a=document.createElement("style");
    var c=document;c.getElementsByTagName("head")[0].appendChild(a);
    if(a.styleSheet){
        a.styleSheet.cssText=b
    }else{
        a.appendChild(c.createTextNode(b))
    }
};

  

javascript insert < link > style

Introducing an external style file with the <link> tag in <head> is relatively simple, and there is no compatibility problem among mainstream browsers:

function includeLinkStyle(url) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.type = "text/css";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}

includeLinkStyle("http://css.xxx.com/home/css/reset.css?v=20101227");

Keywords: PHP IE Attribute Javascript

Added by tensionx on Sat, 12 Oct 2019 22:06:52 +0300