What to do when your <script src> doesn't load

Not exactly a ZIMjs question here...

Is there a way to offer an alternate in the header in case the original dependency doesn't load or is blocked? A kind of try catch alternative.

Thank you in advance for any advice.
James

Hi James. I asked the AI ​​about your problem.

I'm writing his answers below. I hope they help you.

Option 1:

<script src="https://cdn.jsdelivr.net/npm/zimjs@latest" 
        onerror="loadFallback()"></script>
<script>
  function loadFallback() {
    var s = document.createElement('script');
    s.src = '/local/path/zim_fallback.js'; // your backup copy
    document.head.appendChild(s);
  }
</script>

2nd option:

<script>
function loadScript(url) {
  return new Promise(function(resolve, reject) {
    const s = document.createElement("script");
    s.src = url;
    s.onload = resolve;
    s.onerror = reject;
    document.head.appendChild(s);
  });
}

loadScript("https://cdn.jsdelivr.net/npm/zimjs@latest")
  .catch(() => loadScript("/local/path/zim_fallback.js"))
  .then(() => {
    // safe to use zim here
    console.log("ZIM loaded");
  });
</script>

3rd option:

<script src="https://cdn.jsdelivr.net/npm/zimjs@latest"></script>
<script>
if (typeof zim === "undefined") {
  var s = document.createElement("script");
  s.src = "/local/path/zim_fallback.js";
  document.head.appendChild(s);
}
</script>

1 Like

Hi Ferudun,
Thank you so much. This is exactly what I needed. You are very kind to look into this for me. Thank you!
Have a great week.
James

You're welcome. Have a nice week.