-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
adloader.js
91 lines (82 loc) · 2.68 KB
/
adloader.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
82
83
84
85
86
87
88
89
90
91
import includes from 'core-js-pure/features/array/includes.js';
import { logError, logWarn, insertElement } from './utils.js';
const _requestCache = {};
// The below list contains modules or vendors whom Prebid allows to load external JS.
const _approvedLoadExternalJSList = [
'adloox',
'criteo',
'outstream',
'adagio',
'browsi'
]
/**
* Loads external javascript. Can only be used if external JS is approved by Prebid. See https://github.com/prebid/prebid-js-external-js-template#policy
* Each unique URL will be loaded at most 1 time.
* @param {string} url the url to load
* @param {string} moduleCode bidderCode or module code of the module requesting this resource
* @param {function} [callback] callback function to be called after the script is loaded.
*/
export function loadExternalScript(url, moduleCode, callback) {
if (!moduleCode || !url) {
logError('cannot load external script without url and moduleCode');
return;
}
if (!includes(_approvedLoadExternalJSList, moduleCode)) {
logError(`${moduleCode} not whitelisted for loading external JavaScript`);
return;
}
// only load each asset once
if (_requestCache[url]) {
if (callback && typeof callback === 'function') {
if (_requestCache[url].loaded) {
// invokeCallbacks immediately
callback();
} else {
// queue the callback
_requestCache[url].callbacks.push(callback);
}
}
return _requestCache[url].tag;
}
_requestCache[url] = {
loaded: false,
tag: null,
callbacks: []
};
if (callback && typeof callback === 'function') {
_requestCache[url].callbacks.push(callback);
}
logWarn(`module ${moduleCode} is loading external JavaScript`);
return requestResource(url, function () {
_requestCache[url].loaded = true;
try {
for (let i = 0; i < _requestCache[url].callbacks.length; i++) {
_requestCache[url].callbacks[i]();
}
} catch (e) {
logError('Error executing callback', 'adloader.js:loadExternalScript', e);
}
});
function requestResource(tagSrc, callback) {
var jptScript = document.createElement('script');
jptScript.type = 'text/javascript';
jptScript.async = true;
_requestCache[url].tag = jptScript;
if (jptScript.readyState) {
jptScript.onreadystatechange = function () {
if (jptScript.readyState === 'loaded' || jptScript.readyState === 'complete') {
jptScript.onreadystatechange = null;
callback();
}
};
} else {
jptScript.onload = function () {
callback();
};
}
jptScript.src = tagSrc;
// add the new script tag to the page
insertElement(jptScript);
return jptScript;
}
};