UNPKG

@thebigcrunch/sdk

Version:
73 lines (64 loc) 2.66 kB
import { crunch } from "../src/crunch"; import { getConfig } from "../src/config"; (function() { const injectDiv = document.currentScript.previousElementSibling; const injectId = injectDiv.getAttribute("data-tbc-id"); const loadScripts = function loadScripts(scripts) { if (scripts.length === 0) { return; } const script = scripts.shift(); const parentNode = script.parentElement; const newScript = document.createElement("script"); newScript.async = script.async; newScript.textContent = script.textContent; newScript.type = "text/javascript"; newScript.setAttribute("data-tbc-id", injectId); if (script.src) { newScript.src = script.src; parentNode.insertBefore(newScript, script); parentNode.removeChild(script); newScript.onload = () => { loadScripts(scripts); }; } else { parentNode.insertBefore(newScript, script); parentNode.removeChild(script); loadScripts(scripts); } }; const injector = function injector() { // If the previous tag is doesn't have the data attribute then something is weird. if (injectId) { crunch(injectId, (value, cell) => { const xhr = new XMLHttpRequest(); xhr.open("GET", cell.url, true); xhr.onload = () => { const innerHtml = xhr.responseText.replace( /src="\/tbc_sdk.js"/, `src="${getConfig().sdkUrl}"` ); injectDiv.innerHTML = innerHtml; // Run all the scripts in the html. const scriptNodeList = injectDiv.getElementsByTagName( "script" ); // Convert the node list of scripts into an array so we can perform array functions on it. const scripts = []; // iterate backwards ensuring that length is an UInt32 for (let i = scriptNodeList.length >>> 0; i--; ) { scripts[i] = scriptNodeList[i]; } loadScripts(scripts); }; xhr.send(); }); } else { console.error( "The Big Crunch: Couldn't find my tag to insert the crunch data. Please ensure the tag and the script are adjacent." ); } }; injector(); // window.addEventListener('load', injector, false); })();