Three ways for JavaScript to dynamically load CSS

Source: Internet
Author: User
css|javascript| Dynamic | load If you have a lot of related CSS files to load together, or want to dynamically load different CSS files, then the following methods you must be helpful.

The first type: generally used in external CSS files to load the necessary files

Program Code @import URL (style.css);
/* can only be used in a CSS file or in a style label * *

The second: simply load an external CSS file on the page

Program Code Document.createstylesheet (cssfile);

Third: Create a CSS link tag with the CreateElement method

Program Code var head = document.getElementsByTagName (' head '). Item (0);
var style = document.createelement (' link ');
Style.href = ' style.css ';
Style.rel = ' stylesheet ';
Style.type = ' text/css ';
Head.appendchild (style);

here, I used several functions in the project, I hope to be useful!

Program Code function Loadjs (file) {
var Scripttag = document.getElementById (' Loadscript ');
var head = document.getElementsByTagName (' head '). Item (0);
if (Scripttag) head.removechild (Scripttag);
Script = document.createelement (' script ');
SCRIPT.SRC = ".. /js/mi_ "+file+". js ";
Script.type = ' Text/javascript ';
script.id = ' Loadscript ';
Head.appendchild (script);
}

function Loadcss (file) {
var Csstag = document.getElementById (' loadcss ');
var head = document.getElementsByTagName (' head '). Item (0);
if (Csstag) head.removechild (Csstag);
CSS = document.createelement (' link ');
Css.href = ".. /css/mi_ "+file+". css ";
Css.rel = ' stylesheet ';
Css.type = ' text/css ';
css.id = ' loadcss ';
Head.appendchild (CSS);
}

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.