---
title: "CDN Fallback to Local Files: Three Ways to Handle SRI Failures"
description: "What to do when a public CDN script fails to load or fails its SRI check: three copy-paste patterns (global check, onerror chain, import map), plus crossorigin, timeouts and testing."
url: https://cdnping.org/en/blog/public-cdn-fallback-sri-local
language: en
published: 2026-10-29
category: "Edge & CDN"
tags: ["public CDN","SRI","frontend performance","fallback","static assets"]
source: cdnping.org
license: Free to quote and summarize with a link to the url above.
---
# CDN Fallback to Local Files: Three Ways to Handle SRI Failures

When a script you load from a public CDN fails, the most reliable fix is to host a same-version copy on your own site and switch to it the moment the CDN copy fails. To build a CDN fallback to local files, first pick a detection method (check a global variable, or listen for `onerror`), then put the fallback code inline in `<head>`. If you use SRI, the hash, the version number and `crossorigin` must all line up. Otherwise an integrity failure looks exactly like the CDN being down.

Below are three patterns by scenario, followed by a pre-launch test checklist. Choosing a public CDN is a separate question; see [How to choose a public frontend CDN for users in China](/en/learn/choose-public-cdn-china). This article only covers what the page should do after you have chosen one and it misbehaves.

## Why do you still need a fallback when you use a big-name CDN?

You do not control the availability of a public CDN. The same URL can behave very differently across regions, ISPs and times of day. cdnping's [online speed test](/en) measures nine public frontend CDNs in your own browser: "first connection" (including DNS and the TLS handshake) and "round trip" (the median of 3 requests after the connection is reused). The [CDN benchmark](/en/benchmark/cdn) aggregates anonymously reported results. cdnping only started collecting data on October 17, 2026, so the sample window is very short and we do not quote ranking numbers here. Open the speed test from the networks where your users actually are: CDNs with a clearly high first-connection time, or that cannot be reached at all, are the reason to prepare a fallback.

Two more situations are easy to overlook:

- **No error, just hanging.** When DNS resolution misbehaves or packets are dropped, the browser may wait a long time before firing `error`. A synchronous script blocks all further parsing, so users see a blank page rather than an error. To check whether resolution has been tampered with, see [How to tell DNS poisoning from DNS hijacking](/en/blog/dns-pollution-vs-hijacking-detect).
- **Public CDNs no longer give you a shared cache across sites.** Major browsers now partition the HTTP cache by site, so a jQuery file cached for site A must be downloaded again for site B even at the same URL. The old argument that users probably already have it cached no longer holds. What remains is mostly saving your own bandwidth and the CDN's edge coverage.

## How do SRI and fallback relate?

SRI (Subresource Integrity) means adding an `integrity` attribute to a `<script>` or `<link>`. After the download completes, the browser computes the hash. If it does not match the attribute, the browser refuses to execute the resource and fires an `error` event on the element. So from the page's point of view, an SRI failure and a network failure take the same path, and the fallback patterns below handle both.

When you write SRI, three things must hold:

1. **Pin the URL to an exact version.** An address like `jquery@3`, or one with no version, points to content that changes when a new version is published, so the hash will eventually stop matching. Use a full version such as `jquery@3.7.1`, and reference a file that is actually published in the package. Do not use CDN endpoints that merge or minify on the fly, because they regenerate the content.
2. **Cross-origin resources need `crossorigin="anonymous"`.** Without it the browser makes a no-cors request, cannot get a verifiable response, and blocks the resource. This also requires the CDN to return `Access-Control-Allow-Origin`, which common public CDNs normally do. Confirm with `curl -I` before switching providers.
3. **The local copy must be the same file.** When you fall back to the local copy, you can give it the same `integrity` value, which also verifies that your local copy and the CDN copy are the same version.

Commands to generate and check the hash:

```bash
# Compute the sha384 of a local file; the output can go straight into integrity
echo "sha384-$(openssl dgst -sha384 -binary vendor/jquery-3.7.1.min.js | openssl base64 -A)"

# Download the same file from the CDN and compare the hashes
curl -sL https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js \
  | openssl dgst -sha384 -binary | openssl base64 -A; echo

# Check whether the CDN returns CORS headers
curl -sI https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js | grep -i access-control
```

If the two hashes differ, do not ship yet. Usually the local copy is the wrong version, or the CDN path points to a different build artifact.

## Pattern 1: check a global variable, then write in the local copy synchronously

This suits traditional UMD scripts that attach a global after loading, such as `window.jQuery` or `window.Vue`. It is the oldest and simplest approach:

```html
<head>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"
          integrity="sha384-(fill in the value computed above)"
          crossorigin="anonymous"></script>
  <script>
    window.jQuery || document.write(
      '<script src="/vendor/jquery-3.7.1.min.js"><\/script>'
    );
  </script>
  <!-- Scripts that depend on jQuery go after this -->
  <script src="/js/app.js"></script>
</head>
```

A few details:

- Inside the string, write `</script>` as `<\/script>`. Otherwise the HTML parser ends the outer script early.
- Using `document.write` here is deliberate. It inserts synchronously during parsing, which guarantees the following `app.js` runs after jQuery. If you insert the script dynamically with `document.createElement('script')`, it will not block parsing, so `app.js` may run first and throw `$ is not defined`.
- Browsers restrict cross-origin scripts inserted via `document.write` on slow connections, but the path written here is same-origin and local, so it is not affected.
- If the first `<script>` hangs rather than fails, this check only runs after it times out, and the synchronous pattern has no way to add a timeout. If blank-screen time matters to you, see Pattern 2.

## Pattern 2: chain several sources with onerror, and add a timeout

This fits cases where you want to try "primary CDN → backup CDN → your own site" in order, or where the page already loads its scripts asynchronously. Put the loader inline at the very top of `<head>`, not in an external file, because an external file can fail to load too:

```html
<head>
<script>
  function loadWithFallback(urls, opts, done) {
    var i = 0;
    function next() {
      if (opts.test && opts.test()) return done && done(null);   // already available
      if (i >= urls.length) return done && done(new Error('all sources failed'));
      var url = urls[i++], finished = false;
      var s = document.createElement('script');
      s.src = url;
      if (opts.integrity) s.integrity = opts.integrity;
      if (!url.startsWith('/')) s.crossOrigin = 'anonymous';
      var timer = setTimeout(function () { fail('timeout'); }, opts.timeout || 3000);
      function fail(reason) {
        if (finished) return; finished = true; clearTimeout(timer);
        s.onload = s.onerror = null;
        console.warn('[fallback]', reason, url);
        next();
      }
      s.onload = function () {
        if (finished) return; finished = true; clearTimeout(timer);
        if (opts.test && !opts.test()) return next();   // loaded, but the content is wrong
        done && done(null, url);
      };
      s.onerror = function () { fail('error'); };      // network failure or SRI mismatch
      document.head.appendChild(s);
    }
    next();
  }
</script>
<script>
  loadWithFallback([
    'https://cdn.jsdelivr.net/npm/vue@3.5.13/dist/vue.global.prod.js',
    'https://unpkg.com/vue@3.5.13/dist/vue.global.prod.js',
    '/vendor/vue-3.5.13.global.prod.js'
  ], {
    integrity: 'sha384-(fill in the real value; all three URLs must be the same file)',
    test: function () { return !!window.Vue; },
    timeout: 3000
  }, function (err, url) {
    if (err) { /* show a degraded-mode notice, or report it */ return; }
    window.__vueSource = url;   // record which source was finally used, for stats
    startApp();
  });
</script>
</head>
```

Things to watch out for:

- **Do not set `async = false` on the dynamic scripts.** With it, the browser executes them in insertion order, so a hanging first source blocks the backups behind it and the timeout is wasted. Let the `done` callback guarantee execution order.
- **After a timeout, the original request is not cancelled.** If it later succeeds, the script runs a second time. For libraries that set a global, the second run overwrites the first global object, and plugins attached to the old object are lost. So do not set the timeout too short. About 3 seconds is a starting point; tune it against your speed-test data. Always start application code from the `done` callback and never assume ordering.
- **Backup sources use different path rules.** The URL structure for the same npm package is not necessarily the same across CDNs. Verify the hash of every address separately with the curl commands above.
- **CSP.** If the site uses Content-Security-Policy, inline scripts need a nonce or hash, and `script-src` must list the domains of all backup CDNs. Otherwise the fallback request is blocked by CSP and looks like a load failure in the console.
- **CSS works the same way.** `<link rel="stylesheet">` also fires `error`, so you can switch sources with the same idea. An easier approach is to serve critical CSS from your own site; see how fonts are handled in [Self-hosting Google Fonts for users in China](/en/blog/self-host-google-fonts-china).

## Pattern 3: how do you fall back with ES modules and import maps?

Mapping `vue` to a CDN URL with `<script type="importmap">` is convenient, but each import map entry takes only one URL, and there is no "if it fails, try the next one" syntax. If any dependency of a static `import` fails to load, the whole module graph does not execute. There are two workable approaches.

**Approach A: use dynamic import with try/catch for critical entry points.**

```html
<script type="module">
  async function importWithFallback(urls) {
    for (const url of urls) {
      try { return await import(url); }
      catch (e) { console.warn('[fallback]', url, e); }
    }
    throw new Error('all sources failed');
  }
  const { createApp } = await importWithFallback([
    'https://cdn.jsdelivr.net/npm/vue@3.5.13/dist/vue.esm-browser.prod.js',
    '/vendor/vue-3.5.13.esm-browser.prod.js'
  ]);
  createApp({ /* ... */ }).mount('#app');
</script>
```

This only works for entry points you import directly. If the library itself imports other CDN addresses internally, a failure in those sub-dependencies also fails the whole `import()`, and everything switches to the local copy. So the local copy should preferably be a self-contained build.

**Approach B: probe first, then generate the import map.** An import map must be inserted before the first module starts loading. In `<head>`, a small inline script can send a request with a short timeout to the primary CDN, decide from the result whether the import map points to the CDN or to local files, and then `document.head.appendChild` a script with `type="importmap"`. The cost is one extra request's wait on first paint, so use it only when you have many dependencies and hand-writing multiple `import()` calls is impractical. Newer browsers support an `integrity` field in import maps; check the MDN compatibility table before relying on it.

## How do the three patterns compare with bundling into your own site?

| Approach | Best for | Handles hangs? | Maintenance cost | Main risk |
|---|---|---|---|---|
| Global variable + document.write | Old projects, a few UMD scripts | No, waits for the browser timeout | Low | Blank-screen time is unpredictable |
| onerror chain + timeout | Several backup sources, async loading | Yes | Medium, every source needs its hash checked | Duplicate execution after a timeout |
| Dynamic import / generated import map | ES module projects with no build step | Yes (add your own timeout) | Medium to high | A failed sub-dependency forces a full fallback |
| Bundle into your site at build time | Projects with a build pipeline | Not applicable | Low | You must handle caching and delivery of your own static assets |

If the project already has a bundler, the simplest option is often to bundle the critical dependencies into your own build output, use hashed filenames and cache them for a long time. For how to set the cache headers, see [Cache-Control headers explained](/en/blog/cache-control-headers-guide-cdn). That takes the third-party CDN off the critical path of first paint, and you can drop the fallback code. The cost is that this traffic comes back to your own origin or CDN. If your site is itself slow to reach from China, the problem has only moved; start with [How to diagnose a static site that is slow in China](/en/blog/static-site-slow-in-china-diagnose).

A practical compromise: keep the frameworks and styles needed for first paint on your own site, and keep non-critical large libraries (charts, editors, code highlighting) on the public CDN with SRI and the Pattern 2 fallback.

## How do you verify the fallback actually works before launch?

Fallback code rarely runs, so a mistake is most likely to be discovered when something actually breaks. Go through this checklist before launch:

1. **Simulate an unreachable CDN.** In Chrome DevTools → Network, right-click the CDN request and choose "Block request URL", then reload. Confirm the page still works and that a local `/vendor/...` request appears in the Network panel.
2. **Simulate an SRI failure.** Change one character of the `integrity` value and reload. The console should show an integrity error while the page still works, which shows the fallback caught the integrity failure.
3. **Simulate a hang.** Use your local hosts file to point the CDN domain at an internal address that never responds, or pick a very slow throttling profile in DevTools. Check how long until the page is usable and whether the timeout fires as expected.
4. **Check CSP reports.** On sites with CSP enabled, confirm the console shows no errors like `Refused to load the script`.
5. **Automated regression.** Use Playwright in CI to block CDN requests and assert that the page renders:

   ```js
   // fallback.spec.js
   import { test, expect } from '@playwright/test';

   test('falls back to the local copy when the CDN is unavailable', async ({ page }) => {
     await page.route(/cdn\.jsdelivr\.net|unpkg\.com/, route => route.abort());
     await page.goto('http://localhost:8080/');
     await expect(page.locator('#app')).not.toBeEmpty();
     expect(await page.evaluate(() => window.__vueSource)).toMatch(/^\/vendor\//);
   });
   ```

6. **Leave a trail in production.** Report values like `window.__vueSource` along with your frontend logs so you know how many visits actually used a backup source. If the ratio rises noticeably, compare against the [online speed test](/en) and the [benchmark](/en/benchmark/cdn) to see whether one CDN is struggling on particular networks.

Your own network can also skew the picture. For example, a proxy routing rule may send CDN domains out through an overseas exit. When troubleshooting, work through the [developer network self-check list](/en/blog/developer-network-self-check-2026) to rule out your local machine before blaming the CDN.
