forked from marcbuils/jquery.loadscript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery.loadscript.js
More file actions
Latest commit
82 lines (69 loc) · 2.28 KB
/
Copy pathjquery.loadscript.js
File metadata and controls
82 lines (69 loc) · 2.28 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* PluginAutoLoad: Load your plugins on html DOM without javascript code.
* http://marcbuils.github.com/jquery.pluginautoload/
* https://github.com/leiming/jquery.loadscript
*
* Par Marc Buils ( marc.buils@marcbuils.fr )
* Lei Ming ( poetcoders@gmail.com )
* Sous licence LGPL v3 (http://www.gnu.org/licenses/lgpl-3.0.txt)
*
* v0.1.1 - 09/16/2015:
* First release
*
* v0.1.2 - 12/09/2015;
* Fix lazyLoad bug
*/
$(function(){
// lazyload script
// ref: http://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement
var_loadScript=function(url,params,callback){
varscript=document.createElement("script");
script.type="text/javascript";
if(script.readyState){//IE
script.onreadystatechange=function(){
if(script.readyState=="loaded"||script.readyState=="complete"){
script.onreadystatechange=null;
callback();
}
};
}else{//Others
script.onload=function(){
callback();
};
}
varscriptsProperties=[
'type','src','htmlFor','event','charset','async','defer','crossOrigin','text','onerror'
];
if(typeofparams==='object'&&!$.isEmptyObject(params)){
for(varkeyinparams){
if(params.hasOwnProperty(key)&&$.inArray(key,scriptsProperties)){
script[key]=params[key];
}
}
}
//当设置script的text属性时,需要在加载script DOM节点前设置src属性,否则会执行text文本内容
script.src=url;
document.getElementsByTagName(params['lazyLoad'] ? 'body' : 'head')[0].appendChild(script);
};
$.loadScript=function(p_url,p_params,p_callback){
// Handle p_params is exist
if(arguments.length===2&&typeofarguments[1]==='function'){
p_callback=arguments[1];
p_params={}
}
p_params=p_params||{};
var_return=$.Deferred();
// Call callback if necessary
if(typeof(p_callback)==='function'){
_return.done(function(){
p_callback();
});
}
// Load javascript file
_loadScript(p_url,p_params,function(){
_return.resolve();
});
return_return.promise();
};
})