Two ways to dynamically create css in JS

There are two ways to dynamically create CSS styles:

1. Introducing external css files 
2. Inserting css code snippets 
Dynamically inserting css external files:

  1. function loadStyle ( url ){
  2. var link = document . createElement ( 'link' );
  3. link.type = 'text/css ' ;
  4. link.rel = ' stylesheet ' ;
  5. link.href = url ;
  6. var head = document . getElementsByTagName ( 'head' )[ 0 ];
  7. head.appendChild ( link);
  8. }
  9. loadStyle ( 'test.css' );
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Dynamically load css snippets

  1. function loadCssCode ( code ){
  2. var style = document . createElement ( 'style' );
  3. style.type = 'text/css ' ;
  4. style.rel = ' stylesheet ' ;
  5. //for Chrome Firefox Opera Safari
  6. style.appendChild ( document.createTextNode ( code )) ;
  7. //for IE
  8. //style.styleSheet.cssText = code;
  9. var head = document . getElementsByTagName ( 'head' )[ 0 ];
  10. head.appendChild ( style);
  11. }
  12. loadCssCode ( 'body{background-color:#f00}' );
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

In IE, a tag is regarded as a special tag and cannot access its child elements, so use stylesheet .cssText and use try catch statement to catch errors thrown by IE. The compatible code is as follows:

  1. function loadCssCode(code){
  2. var style = document.createElement( 'style' );
  3. style.type = 'text/css' ;
  4. style.rel = 'stylesheet' ;
  5. try {
  6. // for Chrome Firefox Opera Safari
  7. style .appendChild(document.createTextNode(code));
  8. } catch (ex){
  9. // for IE
  10. style.styleSheet.cssText = code;
  11. }
  12. var head = document.getElementsByTagName( 'head' )[ 0 ];
  13. head.appendChild(style);
  14. }
  15. loadCssCode( 'body{background-color:#f00}' );
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

This way you can add styles to the page in real-time, so you can instantly feel happy on the page

Related: Two ways to dynamically create css in JS