js "include"其他js / css 文件

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 cssjs文件時,應該把css放在前面,好讓界面效果先展現出來

2a.js放在t.htmlbody前,還是body後是有講究的 */

b.js

alert("ok");

b.css

#sp {color:blue;}


發佈了31 篇原創文章 · 獲贊 5 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章