//1、动态添加外部js文件
function loadScript(url){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.body.appendChild(script);
}
//2、动态添加js代码
function loadScriptString(code){
var script = document.createElement("script");
script.type = "text/javascript";
try{
script.appendChild(document.createTextNode(code));
}catch (e) { //兼容IE8-
script.text = code;
}
document.body.appendChild(script);
}
//3、动态添加外部css文件
function loadStyles(url){
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
var head = document.getElementsByTagName("head")[0];
head.appendChild(link);
}
//4、动态添加css代码
function loadStyleString(css) {
var style = document.createElement("style");
style.type = "text/css";
try{
style.appendChild(document.createTextNode(css));
}catch (e) {
style.styleSheet.cssText = css; //兼容IE8-
}
var head = document.getElementsByTagName("head")[0];
head.appendChild(style);
}
loadScript("js/test.js");
//加载完成就可以执行test.js中的内容了
loadScriptString("function sayHi(){alert('hi');}");
sayHi();
loadStyles("css/test.css");
loadStyleString("body{background-color:red}");