Skip to content Skip to sidebar Skip to footer

How To Add Fallback For A Failing CDN

I want to include jQuery from CDN into my code. I also want to create a fallback. My original solution was to check if CDN has failed, and if so use document.write to insert the fa

Solution 1:

I was interested in this idea, so I tried a simple script loading sequence. You set up the array of main/fallback scripts in the sequence you want them to load. Not sure how production ready it is, but let me know if it helps.

const scripts = [{
    main: "https://badlink.com/nothing.js",
    fallback: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
  },
  {
    main: "https://badlink.com/nothing.js",
    fallback: "https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
  }
];

let scriptcounter = 0;

function loadScripts() {
  if (scriptcounter < scripts.length) {
    loadScript(scriptcounter);

  }
}

function loadScript(index, fallback) {
  let thescript = fallback ? scripts[index].fallback : scripts[index].main
  let myScript = document.createElement("script");
  myScript.setAttribute("src", thescript);
  document.body.appendChild(myScript);

  myScript.addEventListener("load", scriptLoaded, false);
  myScript.addEventListener("error", scriptError, false);


  function scriptError() {
    console.log("Script error for ", thescript);
    if (fallback) console.log("Fallback failed, stopping");
    else loadScript(index, true)
  }

  function scriptLoaded() {
    console.log("Script loaded - ", thescript);
    scriptcounter++;
    loadScripts()
  }
}

window.onload = function() {
  loadScripts()
}

Post a Comment for "How To Add Fallback For A Failing CDN"