异步加载 js

异步加载 js,onload 触发 callback 兼容主流浏览器的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* 动态加载JS文件的方法
* Load javascript file method
*
* @param {String} fileName JS文件名
* @param {Function} [callback=function()] 加载成功后执行的回调函数
* @param {String} [into="head"] 嵌入页面的位置
*/
var loadScript = function(fileName, callback, into) {
var isIE = (navigator.appName == "Microsoft Internet Explorer");
var isIE8 = (isIE && navigator.appVersion.match(/8./i) == "8.");

into = into || "head";
callback = callback || function() {};

var script = null;
script = document.createElement("script");
script.id = fileName.replace(/[\./]+/g, "-") + "-js";
script.type = "text/javascript";
script.src = fileName + ".js";

if (isIE8)
{
script.onreadystatechange = function() {
if(script.readyState)
{
if (script.readyState === "loaded" || script.readyState === "complete")
{
script.onreadystatechange = null;
callback();
}
}
};
}
else
{
script.onload = function() {
callback();
};
}

if(document.getElementById(script.id)){
callback();
}else{
if (into === "head") {
document.getElementsByTagName("head")[0].appendChild(script);
} else {
document.body.appendChild(script);
}
}

};
0%