1、动态加载脚本(src 原理,异步,支持跨域)
var loadScript = function (url, callback) { var script = document.createElement("script"); script.src = url; document.getElementsByTagName("head")[0].appendChild(script); if (script.addEventListener) { // for w3c script.onload = function () { script.onload = null; script.parentNode.removeChild(script); callback && callback(); }; } else if (script.readyState) { // for ie script.onreadystatechange = function () { if (script.readyState === "loaded" || script.readyState === "complete") { script.onreadystatechange = null; script.parentNode.removeChild(script); callback && callback(); } }; } else { // for lower brower script.parentNode.removeChild(script); callback && callback(); } };
2、动态加载样式
var loadStyle = function (cssText) { var style = document.createElement("style"); style.type = "text/css"; style.rel = "styleSheet"; try { style.appendChild(document.createTextNode(cssText)); } catch (ex) { // for ie style.styleSheet.cssText = cssText; } document.getElementsByTagName("head")[0].appendChild(style); }; loadStyle("body{background-color:#aaa;}");