@mrporter/inseason-analytics
Version:
In Season Analytics Module
50 lines (44 loc) • 1.81 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = importAnalytics;
exports.findScript = findScript;
exports.createScript = createScript;
function importAnalytics(src) {
return new Promise(function (resolve, reject) {
if (!attempt()) {
var script = findScript(src) || createScript(src);
script.addEventListener('load', attempt);
script.addEventListener('error', attempt);
}
function attempt(event) {
if (event) {
event.target.removeEventListener('load', attempt);
event.target.removeEventListener('error', attempt);
}
if (_typeof(window.NAP) === 'object' && _typeof(window.NAP.WebAn) === 'object') {
resolve(window.NAP.WebAn);
return true;
}
if (event) {
reject(new Error(event.type === 'load' ? 'Expected analytics library at "' + event.target.src + '" to expose "window.NAP.WebAn"' : 'Could not fetch analytics library from "' + event.target.src + '"'));
}
return false;
}
});
}
function findScript(src) {
var scripts = Array.from(document.getElementsByTagName('script'));
return scripts.find(function (el) {
return el.src === src;
});
}
function createScript(src) {
var script = document.createElement('script');
script.async = true;
script.src = src;
document.head.appendChild(script);
return script;
}