jQuery CDN Fallbacks
In this page:
Why Use a Fallback
If the CDN goes down or a network blocks it, every script relying on jQuery breaks at once -- a fallback keeps the page working regardless.
Example: Why Use a Fallback
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
console.log(typeof jQuery === "undefined" ? "jQuery failed to load" : "jQuery loaded");
</script>
</body>
</html>
Basic Fallback Check
A fallback check is just a plain JavaScript if-statement testing typeof jQuery === undefined right after the CDN script tag -- if the CDN failed, jQuery never defined that global, so the check catches it immediately.
Example: Basic Fallback Check
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
if (typeof jQuery === "undefined") {
console.log("CDN failed to load jQuery");
}
</script>
</head>
<body></body>
</html>
Fallback with Script Creation
When the check fails, JavaScript can use document.write() to inject a new <script> tag pointing at a local copy of the jQuery file, loading it as a backup before the rest of the page's scripts run.
Example: Fallback with Script Creation
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
if (typeof jQuery === "undefined") {
document.write('<script src="jquery.min.js"><\/script>');
}
</script>
</head>
<body></body>
</html>
Test the Fallback
Logging a message after the fallback logic confirms which source actually provided jQuery -- useful when testing the fallback path deliberately, for example by blocking the CDN in your browser's dev tools.
Example: Test the Fallback
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
if (typeof jQuery === "undefined") {
console.log("Loaded from local fallback");
} else {
console.log("Loaded from CDN");
}
</script>
</head>
<body></body>
</html>
Keep a Local Copy
Keeping a copy of jquery.min.js inside your own project folder means your site never fully depends on a third-party CDN staying online, at the small cost of one extra file to maintain and update.
Example: Keep a Local Copy
<!DOCTYPE html>
<html>
<head>
<!-- Local fallback copy kept at: /js/jquery.min.js -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
console.log("CDN version:", $.fn.jquery, "- local copy also kept as backup");
</script>
</body>
</html>
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: