Advertisement
TheDemystifier

Anki script - insert Script

Oct 4th, 2023 (edited)
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function insertScript(path, altURL) {
  2.     return new Promise((resolve, reject) => {
  3.         let scriptExists = false;
  4.  
  5.         // Check if script with the same src already exists
  6.         const scripts = document.head.getElementsByTagName('script');
  7.         for (let i = 0; i < scripts.length; i++) {
  8.             if (scripts[i].src === path) {
  9.                 scriptExists = true;
  10.                 scripts[i].onload = resolve;
  11.                 scripts[i].onerror = () => {
  12.                     // If the script fails to load, reload it from altURL
  13.                     let script_online = document.createElement("script");
  14.                     script_online.onload = resolve;
  15.                     script_online.onerror = reject;
  16.                     script_online.src = altURL;
  17.                     scripts[i].parentNode.replaceChild(script_online, scripts[i]);
  18.                 }
  19.                 // Reload the script by setting its src to empty string and then to original path
  20.                 scripts[i].src = '';
  21.                 scripts[i].src = path;
  22.                 break;
  23.             }
  24.         }
  25.  
  26.         if (!scriptExists) {
  27.             // If script doesn't exist, create a new script element
  28.             let script_local = document.createElement("script");
  29.             script_local.onload = resolve;
  30.             script_local.onerror = () => {
  31.                 // If the script fails to load, create a new script element with altURL
  32.                 let script_online = document.createElement("script");
  33.                 script_online.onload = resolve;
  34.                 script_online.onerror = reject;
  35.                 script_online.src = altURL;
  36.                 document.head.appendChild(script_online);
  37.             }
  38.             script_local.src = path;
  39.             document.head.appendChild(script_local);
  40.         }
  41.     });
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement