Bright Labs

Load jQuery from Google's CDN with a local fallback: the snippet, SRI and how to test it

You want jQuery from ajax.googleapis.com, and you want your site to keep working when Google's copy doesn't load. Here's the fix: load the CDN file in a plain script tag with no async or defer, then run a one-line inline check for window.jQuery. If it's missing, load the copy on your own server. Below that sit the details that make it hold up: Subresource Integrity, an exact version, and a quick way to test the fallback before you ship it.

The fallback snippet

Google's Hosted Libraries page gives the jQuery tag with an exact version in the URL. Put your own copy of the same version somewhere on your server, then add the check on the very next line.

Example you write: CDN first, local copy if window.jQuery is missing
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/js/jquery-3.7.1.min.js"><\/script>')</script>

Two small things in there are easy to miss. Copy the escaped <\/script> inside the string exactly as written. And the check looks at window.jQuery, not at a variable you defined yourself.

Every script that uses jQuery goes after these two lines, never before them.

Why the CDN tag can't be async or defer

The whole pattern relies on the browser waiting. MDN's script element reference says scripts without async, defer or type="module" are fetched and executed immediately before the browser continues to parse the page. So your inline check only runs once the browser is done with the CDN tag.

Add async to the CDN tag and that's gone. MDN puts it plainly for async scripts: you get no guarantee that scripts will run in any specific order. With no order guarantee, your check could run before jQuery arrives and load the local copy for no reason, or your own code could run before either copy is there.

There's a second catch with async. MDN's document.write page says a document.write() call from an asynchronously-loaded external script is ignored. Keep the fallback as a plain inline script in the page.

The flip side of a blocking tag: the browser doesn't continue parsing the page until it's done with the CDN tag. If Google's file is slow rather than missing, your page waits for it.

A fallback without document.write

The one-liner above is short, but MDN flags document.write(): the "method is strongly discouraged." It also says to avoid it and, where possible, replace it in existing code. The same page notes that browsers are explicitly allowed to skip script elements inserted with it. That's not a risk you want in the one line that's supposed to save you.

The replacement is to create the script element yourself and start your own code when it has loaded. MDN's script reference says an error event is sent to the element if the script is blocked, and a load event otherwise, so you can hook onload.

Example you write: DOM fallback, with your jQuery code started from one function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
  function startApp() {
    // your code that uses jQuery
  }
  if (window.jQuery) {
    startApp();
  } else {
    var s = document.createElement('script');
    s.src = '/js/jquery-3.7.1.min.js';
    s.onload = startApp;
    document.head.appendChild(s);
  }
</script>

The catch: this snippet only starts startApp. Put everything that needs jQuery inside startApp, or load your own scripts from there too. Load your jQuery plugins from there as well, not as separate tags further down the page.

Add Subresource Integrity, so a changed file also falls back

A fallback covers a file that doesn't arrive. Subresource Integrity covers a file that arrives but isn't the one you expected. MDN's description: "It works by allowing you to provide a cryptographic hash that a fetched resource must match." If it doesn't match, the browser will refuse to load the resource and return a network error.

That works nicely with the fallback. A refused file never defines window.jQuery, so your check loads the local copy, the same as when the CDN is down.

Two attributes go on the CDN tag: integrity with the hash, and crossorigin. MDN says cross-origin requests that use subresource integrity must use the CORS protocol, and that you must include the crossorigin attribute in your markup. Leave crossorigin off and the request will always fail, which means you'd quietly be on the fallback every time.

To get the hash, download the exact file from the CDN URL and run the command from MDN's SRI page on it. Hash the CDN file itself, and keep your local copy as that same file.

Hash command, copied from MDN's Subresource Integrity page
cat FILENAME.js | openssl dgst -sha384 -binary | openssl base64 -A
Example you write: the CDN tag with SRI (paste your own hash after sha384-)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"
        integrity="sha384-PASTE-YOUR-HASH-HERE"
        crossorigin="anonymous"></script>

Pin one exact version on both sides

The fallback only helps if both files are the same jQuery. Use the full version number in the CDN URL, and name your local file after it so a later upgrade can't drift on one side only.

Don't use the short version links either. Google's Hosted Libraries page says it deprecated and stopped updating the automatic version aliases some time ago, so they will forever refer to an old version.

Check that the version you want is really on Google's list. Its jQuery list starts 3.7.1, 3.7.0, 3.6.4, and some versions are skipped on purpose: "3.3.0, 2.1.2, 1.2.5 and 1.2.4 are not hosted due to their short and unstable lives in the wild." If the version you need isn't on Google's list, serve your own copy only.

Is Google's copy still worth loading first?

If you picked the Google copy hoping visitors already had it cached from another site, check that reasoning. Chrome's write-up on cache partitioning says Chrome will partition its HTTP cache starting in Chrome 86, with a key built from the top-level site and the current-frame site. In its example, the same file loaded on a different site is not a cache hit, because the key doesn't match.

Google describes Hosted Libraries as a stable, reliable, high-speed, globally available content distribution network. That's still a reasonable reason to use it. But if your own server is fast, serving only your own copy is a fair choice too: one file, one origin, nothing to fall back from.

Test the fallback before you ship

A fallback you've never seen fire is a guess. Try both failure modes on a local or staging copy:

Sources

Questions

Can I add async to the Google jQuery tag and keep the fallback?

Not with this pattern. MDN says async scripts give no guarantee of run order, so your window.jQuery check can run before jQuery arrives. MDN also says a document.write() call from an asynchronously-loaded external script is ignored. Keep the CDN tag as a plain script tag.

Is document.write still OK for the jQuery fallback?

MDN says its use is strongly discouraged and that browsers are explicitly allowed to skip script elements it inserts. The createElement version in this post avoids it. The trade-off is that you start your jQuery code from the onload handler.

Does Subresource Integrity break the fallback?

No, it feeds it. If the hash doesn't match, the browser refuses the file and returns a network error, so window.jQuery stays undefined and your local copy loads. Do include the crossorigin attribute: MDN says cross-origin SRI requests must use CORS.

Can I use a short version URL so I get updates automatically?

No. Google's page says it deprecated and stopped updating the automatic version aliases some time ago, so they keep pointing at an old version. Use the full version in the URL and match your local file to it.

Related