異步加載JSjavascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>異步加載js</title>
</head>
<body>
<script>
//異步加載JS函數
// 實現思想:動態建立script標籤,插入到文檔中,而後執行callback函數
//url爲請求的JS文件的地址,callback爲請求成功時的回調函數
function loadScript(url,callback){
//動態建立script標籤
var script = document.createElement("script");
script.type = "text/javascript";
//判斷外部的JS文件是否加載完成(此處須要解決瀏覽器的兼容問題)
if(script.readyState){
script.onreadystatechange = function(){
if(script.readyState == 'loaded' || script.readyState == 'complete'){
script.onreadystatechange = null;
callback();
}
}
}else{
script.onload = function(){
callback();
}
}
script.src = url;
//執行腳本文件
document.body.appendChild(script);
}
//調試程序
// loadScript("1.js",function(){
// test();
// });
</script>
</body>
</html>