JavaScript 动态加载脚本和样式的方法
一动态脚本
当网站需求变大,脚本的需求也逐步变大;我们不得不引入太多的JS脚本而降低了整站的性能;
所以就出现了动态脚本的概念,在适时的时候加载相应的脚本;
1.动态引入js文件
varflag=true;
if(flag){
loadScript('browserdetect.js');//调用函数,引入路径;
}
functionloadScript(url){
varscript=document.createElement('script');//创建script标签;
script.type='text/javascript';//设置type属性;
script.src=url;//引入url;
document.getElementsByTagName('head')[0].appendChild(script);//将script引入<head>中;
}
2.动态执行js代码
varscript=document.createElement('script');
script.type='text/javascript';
vartext=document.createTextNode("alert('Lee')");//设置script标签内容;IE会报错;
script.appendChild(text);
document.getElementsByTagName('head')[0].appendChild(script);
//PS:IE浏览器认为script是特殊元素,不能再访问子节点;
//为了兼容,可以使用text属性来代替;
functionloadScriptString(code){
varscript=document.createElement("script");
script.type="text/javascript";
try{
//IE浏览器认为script是特殊元素,不能再访问子节点;报错;
script.appendChild(document.createTextNode(code));//W3C方式;
}catch(ex){
script.text=code;//IE方式;
}
document.body.appendChild(script);
}
//调用;
loadScriptString("functionsayHi(){alert('hi')}");
二动态样式
为了动态的加载样式表,比如切换网站皮肤;
样式有两种方式进行加载,一种是<link>标签,一种是<style>标签;
1.动态引入link文件
varflag=true;
if(flag){
loadStyles('basic.css');//调用函数,引入路径;
}
functionloadStyles(url){
varlink=document.createElement('link');
link.rel='stylesheet';
link.type='text/css';
link.href=url;
document.getElementsByTagName('head')[0].appendChild(link);
}
2.动态执行style代码
varflag=true;
if(flag){
varstyle=docuemnt.createElement('style');
style.type='text/css';
document.getElementsByTagName('head')[0].appendChild(style);
insertRule(document.styleSheets[0],'#box','background:red',0);
}
functioninsertRule(sheet,selectorText,cssText,position){
//如果是非IE;
if(sheet.insertRule){
sheet.insertRule(selectorText+"{"+cssText+"}",position);
//如果是IE;
}elseif(sheet.addRule){
sheet.addRule(selectorText,cssText,position);
}
}
//动态执行style2
functionloadStyleString(css){
varstyle=document.createElement("style");
style.type="text/css";
try{
//IE会报错;不允许向<style>元素添加子节点;
style.appendChild(document.createTextNode(css));
}catch(ex){
//此时,访问元素的StyleSheet属性,该属性有有一个cssText属性,可以接受CSS代码;
style.styleSheet.cssText=css;
}
varhead=document.getElementsByTagName("head")[0];
head.appendChild(style);
}
//调用;
loadStyleString("body{background-color:red}");