Dynamically loading CSS files, this is often used, generally engaged in front end, we first thought is to use JS to achieve, indeed, JS can easily control the dynamic insertion of CSS stylesheet files, the following two methods: the use of <style> tags inserted page style, Dynamic introduction of external styles in a page is a common way to dynamically load CSS.
First, use <style> tags to insert page styles
This uses the Yui plug-in a method, effectively solve the major browser compatibility problems, mainly using Style.appendchild ( document.createTextNode (styles)), using createTextNode to add CSS code to <style> tags, look at the code:
code is as follows |
copy code |
<script> function Includestyleelement (styles,styleid) { if ( document.getElementById (Styleid)) { return } var style = document.createelement ("style"); Style.id = Styleid; //Set properties for IE /*if (Isie ()) { Style.type = "Text/css"; Style.media = "screen" }*/ (document.getelemen Tsbytagname ("Head") [0] | | document.body). appendchild (style); if (style.stylesheet) {//for ie Style.styleSheet.cssText = styles; } else {//for The Internet Consortium Style.appendchild (d Ocument.createtextnode (styles)); } var styles = "#div {background-color: #FF3300; Color: #FFFFFF} "; Includestyleelement (Styles, "NewStyle"); </script> |
This way the elements in the page can be applied directly, regardless of whether or not your elements are appended by the script.
Second, the introduction of external styles in the page:
Using <link> tags in
The code is as follows |
Copy Code |
<script> 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 ("/css/reset.cssv=20140222" </script> |
If you use less style, this method seems to be a bit of a fuss, just for reference.