<html>
<head>
<script type="text/javascript">
/**=========================================**
| 异步延时加载js/css文件
| @example loadasync("http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js");
| @author liuensong@gmail.com
| @param string url js/css链接地址
| @return 新生成element对象/null
**=========================================**/
function loadasync(url){
var elt=null, head=null, type=null;
if(url){
head = document.getElementsByTagName("head")[0];
switch(url.split(".").pop()){
case "css":
elt = document.createElement("link");
elt.rel = "stylesheet";
elt.href = url;
break;
case "js":
elt = document.createElement("script");
elt.type = "text/javascript";
elt.src = url;
break;
default:
//something...
}
if(elt!=null && (typeof elt)=="object"){
head.appendChild(elt);
}
}
return elt;
}
/**=========================================**
| 判断js/css文件是否已加载
| @example isload("jquery.min.js");
| @author liuensong@gmail.com
| @param string fname js/css文件名
| @return bool true/false
**=========================================**/
function isload(fname){
var isload = false;
var tags = {"js":"script", "css":"link"};
var tagname = tags[fname.split(".").pop()];
if(tagname != undefined){
var elts = document.getElementsByTagName(tagname);
for(i in elts){
if((elts[i].href && elts[i].href.toString().indexOf(fname)!="-1") ||
(elts[i].src && elts[i].src.toString().indexOf(fname)!="-1")){
isload = true;
}
}
}
return isload;
}
//console.debug(loadasync("http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"));
//console.debug(isload("jquery.min.js"));
</script>
</head>
<body>
<a href="javascript:;" οnclick="loadasync('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');">loadasync</a>
<a href="javascript:;" οnclick="isload('jquery.min.js');">isload</a>
</body>
</html>
javascript异步延时加载及判断是否已加载js/css文件
最新推荐文章于 2021-10-28 19:47:33 发布