1.動態載入腳本 <script type="text/javascript"> function loadScript(url){ var script=document.createElement("script"); script.type="text/javascript"; script.
1.動態載入腳本
<script type="text/javascript">
function loadScript(url){
var script=document.createElement("script");
script.type="text/javascript";
script.src=url;
document.body.appendChild(script);
}
loadScript("js/side-panel.js");
2.XHR Injection 使用動態創建script元素,來寫入腳本,在某些情況下可能比上一種方法要快些。
/*var xhrObj = new XMLHttpRequest();
xhrObj.onreadystatechange = function(){
if(xhrObj.readyState == 4&&xhrObj.status==200){
var scriptElem = document.createElement("script");
document.getElementsByTagName("head")[0].appendChild(scriptElem);
scriptElem.text = xhrObj.responseText;
}
};
xhrObj.open("GET", "js/pop.js", true);
xhrObj.send("");
3.XHR Eval
顧名思義,通過XHR讀取腳本,通過Eval令腳本生效。
var xhrObj = getxhr();
xhrObj.onreadystatechange = function(){
if(xhrObj.readyState == 4 && xhrObj.status==200){
eval(xhrObj.responseText);
}
};
function getxhr(){
var xhr=null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
else{
xhr=new ActiveXObject("Microsoft.XMLHttp")
}
return xhr;
}
xhrObj.open("GET", "js/pop.js", true);
xhrObj.send("");
4.Script Defer
原生方案。利用defer屬性來防止腳本阻塞。
代碼如下:
1 |
<script defer src="A.js"></script> |
defer是最簡單的方法,現在主流的瀏覽器已經支持