JS code for dynamically loading CSS style files

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.