t.html
<html>
<body>
<label id="sp">aaa</label>
</body>
<script type="text/javascript" src="a.js"></script>
</html>
a.js
function $import(path, type){
var i,
base,
src = "a.js", //html中已經加載的js文件,爲的是取得base路徑
scripts = document.getElementsByTagName("script");
for (i = 0; i < scripts.length; i++) { //遍歷html中已經加載的js,取得整個應用加載js的base路徑
if (scripts[i].src.match(src)) {
base = scripts[i].src.replace(src, "");
break;
}
}
if (type == "css") {
document.write("<" + "link href=\"" + base + path + "\" rel=\"stylesheet\" type=\"text/css\"></" + "link>");
} else {
document.write("<" + "script src=\"" + base + path + "\"></" + "script>");
}
}
$import('b.css', 'css');
$import('b.js', 'js');
/*注意2個問題:
*1:同時import css和js文件時,應該把css放在前面,好讓界面效果先展現出來
2:a.js放在t.html的body前,還是body後是有講究的 */
b.js
alert("ok");
b.css
#sp {color:blue;}