-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfetch-script.js
More file actions
75 lines (58 loc) · 1.86 KB
/
fetch-script.js
File metadata and controls
75 lines (58 loc) · 1.86 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
/**
* Source: https://github.com/Adobe-Marketing-Cloud/fetch-script
*/
function getScriptId() {
return 'script_' + Date.now() + '_' + Math.ceil(Math.random() * 100000);
}
function createScript(url, id) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.id = id;
script.src = url;
return script;
}
function removeScript(id) {
const script = document.getElementById(id);
const parent = script.parentNode;
try {
parent && parent.removeChild(script);
} catch (e) {
// ignore
}
}
function appendScript(script) {
const firstScript = document.getElementsByTagName('script')[0];
firstScript.parentNode.insertBefore(script, firstScript);
}
function fetchScriptInternal(url, options, Promise) {
return new Promise(function(resolve, reject) {
const timeout = options.timeout || 5000;
const scriptId = getScriptId();
const script = createScript(url, scriptId);
const timeoutId = setTimeout(function() {
reject(new Error('Script request to ' + url + ' timed out'));
removeScript(scriptId);
}, timeout);
const disableTimeout = function(timeoutId) { clearTimeout(timeoutId); };
script.addEventListener('load', function(e) {
resolve({ok: true});
disableTimeout(timeoutId);
removeScript(scriptId);
});
script.addEventListener('error', function(e) {
reject(new Error('Script request to ' + url + ' failed ' + e));
disableTimeout(timeoutId);
removeScript(scriptId);
});
appendScript(script);
});
}
function fetchScript(settings) {
settings = settings || {};
return function (url, options) {
options = options || {};
return fetchScriptInternal(url, options, settings.Promise || Promise);
};
}
module.exports = fetchScript;