At present, the mainstream front-end deployment mode is basically to package static resources and upload them to the CDN server, and may also refer to some online public resource libraries. This may be a problem: if the CDN server is down, the page will not be accessible. In my previous work, THE author encountered the problem that the third-party resource public CDN server was down. At that time, the temporary solution was to modify the address and republish it, during which it was unavailable for a certain period of time. For small and medium-sized companies, it is ok to have fewer systems, but it is difficult to change many systems.

So from the front end point of view, is there any better solution?

In fact, the idea is very simple, when the current static resource fails to load automatically to another place to reload the resource. Based on this idea, we can upload static resources to multiple CDN servers, one for primary use and one for backup, so that different CDN services have the same request path. In this example, CDN A is used as the primary domain name, and CDN B is used as the backup domain name.

We can add an onCdnError event to all script and link tags, and then define a global onCdnError event in the window. Then get the link that the current resource failed in the custom event, replace it with the standby CDN address, and reload the resource once.

Main implementation logic:

// Links to static resources
var staticMap = {
  link: "href".script: "src"};// <link onerror="onCdnError(this)" href="https://cdn-a.com/index.css" rel="stylesheet"/>
// <script onerror="onCdnError(this)" href="https://cdn-a.com/index.js"></script>
window.onCdnError = function (e) {
  const nodeName = e.nodeName.toLowerCase();
  const srcName = staticMap[nodeName];
  if(! srcName) {return;
  }
  // Get the link where the current load failed
  let link = e[srcName];
  if(! link)return;
  if (link.includes("cdn-a.com")) {
    link = link.replace("cdn-a.com"."cdn-b.com");

    // Create a script or link tag and insert it into the head
    const head = document.head || document.getElementsByTagName("head") [0];
    const el = document.createElement(nodeName);
    if (el === "link") {
      el.rel = "stylesheet";
    }
    el[srcName] = link;
    el.onerror = function () {
      window.onCdnError(el);
    };
    el.setAttribute("crossorigin"."anonymous");
    head.appendChild(el);
  } else {
    // It may already be CDN b, and CDN B has already died, so we can do some prompt processing
    / /... do something}};Copy the code