Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function insertScript(path, altURL) {
- return new Promise((resolve, reject) => {
- let scriptExists = false;
- // Check if script with the same src already exists
- const scripts = document.head.getElementsByTagName('script');
- for (let i = 0; i < scripts.length; i++) {
- if (scripts[i].src === path) {
- scriptExists = true;
- scripts[i].onload = resolve;
- scripts[i].onerror = () => {
- // If the script fails to load, reload it from altURL
- let script_online = document.createElement("script");
- script_online.onload = resolve;
- script_online.onerror = reject;
- script_online.src = altURL;
- scripts[i].parentNode.replaceChild(script_online, scripts[i]);
- }
- // Reload the script by setting its src to empty string and then to original path
- scripts[i].src = '';
- scripts[i].src = path;
- break;
- }
- }
- if (!scriptExists) {
- // If script doesn't exist, create a new script element
- let script_local = document.createElement("script");
- script_local.onload = resolve;
- script_local.onerror = () => {
- // If the script fails to load, create a new script element with altURL
- let script_online = document.createElement("script");
- script_online.onload = resolve;
- script_online.onerror = reject;
- script_online.src = altURL;
- document.head.appendChild(script_online);
- }
- script_local.src = path;
- document.head.appendChild(script_local);
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement