JavaScript 动态加载脚本和样式的方法

前端之家收集整理的这篇文章主要介绍了JavaScript 动态加载脚本和样式的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一 动态脚本

当网站需求变大,脚本的需求也逐步变大;我们不得不引入太多的JS脚本而降低了整站的性能; 所以就出现了动态脚本的概念,在适时的时候加载相应的脚本;

1.动态引入js文件

调用函数,引入路径; } function loadScript(url){ var script = document.createElement('script'); // 创建script标签; script.type = 'text/javascript'; // 设置type属性; script.src = url; // 引入url; document.getElementsByTagName('head')[0].appendChild(script); // 将script引入中; }

2.动态执行js代码

标签内容;IE会报错; script.appendChild(text); document.getElementsByTagName('head')[0].appendChild(script);

// PS:IE浏览器认为script是特殊元素,不能再访问子节点;
// 为了兼容,可以使用text属性来代替;
function loadScriptString(code){
var script = 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("function sayHi(){alert('hi')}");

二 动态样式

为了动态的加载样式表,比如切换网站皮肤; 样式有两种方式进行加载,一种是标签,一种是@H_404_23@标签;

1.动态引入link文件

调用函数,引入路径; } function loadStyles(url){ var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = url; document.getElementsByTagName('head')[0].appendChild(link); }

2.动态执行style代码

Box','background:red',0); } function insertRule(sheet,selectorText,cssText,position){ // 如果是非IE; if(sheet.insertRule){ sheet.insertRule(selectorText+"{"+cssText+"}",position); // 如果是IE; }else if(sheet.addRule){ sheet.addRule(selectorText,position); } }
404_23@元素添加子节点; style.appendChild(document.createTextNode(css)); }catch(ex){ // 此时,访问元素的StyleSheet属性,该属性有有一个cssText属性,可以接受CSS代码; style.styleSheet.cssText = css; } var head = document.getElementsByTagName("head")[0]; head.appendChild(style); } // 调用; loadStyleString("body {background-color:red}");

猜你在找的JavaScript相关文章