Tag Archives: stylesheet

JavaScript / JS native dynamic introduction of external CSS files and dynamic insertion of CSS code fragments

there are two ways to dynamically create CSS styles:
1. Introduce external CSS files
2. Insert CSS snippet
how to insert CSS external files dynamically:

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

dynamically loads CSS snippet

function loadCssCode(code){
    var style = document.createElement('style');
    style.type = 'text/css';
    style.rel = 'stylesheet';
    //for Chrome Firefox Opera Safari
    style.appendChild(document.createTextNode(code));
    //for IE
    //style.styleSheet.cssText = code;
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(style);
}
loadCssCode('body{background-color:#f00}');

IE & lt; link> The tag is considered a special tag and its children cannot be accessed, so stylesheet.csstext is used, and errors thrown by IE are caught using a try catch statement, with the following compatible code:

function loadCssCode(code){
var style = document.createElement('style');
    style.type = 'text/css';
    style.rel = 'stylesheet';
    try{
        //for Chrome Firefox Opera Safari
        style .appendChild(document.createTextNode(code));
    }catch(ex){
        //for IE
        style.styleSheet.cssText = code;
    }
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(style);
}
loadCssCode('body{background-color:#f00}');

adds styles to the page in real time, so you can react instantly on the page.