JS 动态加载 CSS 在可换主题的界面中具有很重要的意义,用户可以根据自己的浏览习惯选择自己喜欢的页面显示方式,动态加载 CSS 的方法主要有三种,下面详细说明。如果你有很多关联的CSS文件要一起加载,或者想动态的加载不同的CSS文件,那么下面的方法你一定对你有帮助。
(1)使用JavaScript动态加载Js文件
/*JavaScript动态加载Js文件*/
var scriptNode = document.createElement('script';
scriptNode.src = 'proxy.js?t='+new Date(.getTime(;/*附带时间参数,防止缓存*/
document.head.appendChild(scriptNode;
(2)使用JavaScript动态加载css文件
/*JavaScript动态加载Css文件*/
var cssNode = document.createElement('link';
cssNode.rel = 'stylesheet';
cssNode.type = 'text/css';
cssNode.media = 'screen';
cssNode.href = 'style.css?t='+new Date(.getTime(;/*附带时间参数,防止缓存*/
document.head.appendChild(cssNode;
(3)Jquery动态加载Js和Css扩展
$.extend({
includePath: '',
include: function(file {
var files = typeof file == "string" ? [file]:file;
for (var i = 0; i < files.length; i++ {
var name = files[i].replace(/^\s|\s$/g, "";
var att = name.split('.';
var ext = att[att.length - 1].toLowerCase(;
var isCSS = ext == "css";
var tag = isCSS ? "link" : "script";
var attr = isCSS ? " type='text/css' rel='stylesheet' " : " language='javascript' type='text/javascript' ";
var link = (isCSS ? "href" : "src" + "='" + $.includePath + name + "'";
if ($(tag + "[" + link + "]".length == 0 document.write("<" + tag + attr + link + "></" + tag + ">";
}
}
};
使用方法:
$.include('www.feishuai.vip/file/ajaxa.js';
$.include('www.feishuai.vip/file/ajaxa.css';
或者:
$.includePath='www.feishuai.vip/file/';
$.include(['ajaxa.js','ajaxa.js'];