-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloadscript.js
More file actions
48 lines (42 loc) · 1.05 KB
/
loadscript.js
File metadata and controls
48 lines (42 loc) · 1.05 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
const loadScript = (src, callback = null) => {
// return if no arguments
if (!src) {
return;
}
// vars
const script = document.querySelector(`script[src^="${src}"]`);
const addLoadEvent = (el) => {
el.addEventListener("load", function() {
this.readystate = true;
if (callback) {
callback();
}
});
};
// add script
if (!script) {
// Script doesn't exists in DOM, create script element
const el = Object.assign(document.createElement("script"), {
src,
readyState: false,
});
// append script to document head
document.head.appendChild(el);
// load event
addLoadEvent(el);
} else {
if (script.readystate === false) {
// If script exists in DOM, but not yet loaded
addLoadEvent(script);
} else {
// If script exists in DOM and fully loaded
if (callback) {
callback();
}
}
}
};
const loadScripts = (scripts) => {
scripts = Array.isArray(scripts) ? scripts : [scripts];
scripts.forEach((script) => HE.loadScript(script));
};