Javascript之动态加载脚本和样式
//动态加载脚本
function loadScript(url){
let script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.body.appendChild(script);
}
loadScript();
确定脚本加载完成
function loadScriptString(code){
let script = document.createElement("script");
script.type = "text/javascript";
try{
script.appendChild(document.createTextNode(code));
}catch(ex){
script.text = code; //兼容IE
}
document.body.appendChild(script);
}
loadScriptString("function sayHi(){alert('Hi!');}");
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//动态加载样式
function loadStyle(url){
let link = document.createElement("style");
link.rel = "stylesheet";
link.href = url;
link.type = "text/css";
let head = document.querySelectorAll("head")[0];
head.appendChild(link);
}
//loadStyle();
//检测样式表加载完成
function loadStyleString(code){
let style = document.createElement("style");
style.type = "text/css";
try{
style.appendChild(document.createTextNode(code));
}catch(ex){
style.stylesheet.cssText = code; //兼容IE
}
}
loadStyleString("body{background-color:orange;}");