-
Notifications
You must be signed in to change notification settings - Fork 3
/
jquery.loadscript.js
81 lines (68 loc) · 2.16 KB
/
jquery.loadscript.js
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
/**
* 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 ( [email protected] )
* Lei Ming ( [email protected] )
* 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) {
var script = 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();
};
}
var scriptsProperties = [
'type', 'src', 'htmlFor', 'event', 'charset', 'async', 'defer', 'crossOrigin', 'text', 'onerror'
];
if (typeof params === 'object' && !$.isEmptyObject(params)) {
for (var key in params) {
if (params.hasOwnProperty(key) && $.inArray(key, scriptsProperties)) {
script[key] = params[key];
}
}
}
document.getElementsByTagName(params['lazyLoad'] ? 'body' : 'head')[0].appendChild(script);
script.src = url;
};
$.loadScript = function (p_url, p_params, p_callback) {
// Handle p_params is exist
if (arguments.length === 2 && typeof arguments[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();
};
})