动态脚本
加载外部脚本
方式一,直接写代码:
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "js/test.js";
document.body.appendChild(script);
方式二,封装成函数:
function createScript(url){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.body.appendChild(script);
};
createScript("js/test.js");
行内编写脚本
创建script元素并往其中写代码:
function loadScriptString(code){ var script = document.createElement("script"); script.type = "text/javascript"; try { script.appendChild(document.createTextNode(code)); } catch (ex){ script.text = code; } document.body.appendChild(script); }
loadScriptString("function sayHi(){alert('hi');}");