liveBook · Manning

CDN fallback

As explained in Pro ASP.NET Core 7, Tenth Edition

CDN fallback is a resource-loading technique that loads a local asset when a corresponding asset cannot be obtained or verified from a content delivery network.

CDN fallback loads a local JavaScript file when a CDN script fails its test. In an ASP.NET Core Razor layout, set `src` to the CDN URL, `asp-fallback-src` to the local file, and `asp-fallback-test` to an expression that should be true after the script runs. section 26.4.1

Listing 26.13 CDN fallback in the _SimpleLayout.cshtml file in the Views/Shared folder
<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <script src=
      "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
         asp-fallback-src="/lib/jquery/jquery.min.js" 
         asp-fallback-test="window.jQuery">
    </script>
</head>
<body>    
    <div class="m-2">
        @RenderBody()
    </div>
</body>
</html>

A layout loads jQuery 3.6.0 from a CDN, tests `window.jQuery`, and names `/lib/jquery/jquery.min.js` as its fallback. section 26.4.1

Test it before the CDN fails for real: change `src` to a nonexistent filename and inspect browser network requests. A failed CDN request should be followed by the local request. Do not combine this fallback with asynchronous script loading; the test may run before the CDN script executes and needlessly load the local copy. section 26.4.1

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Works through tag-helper attributes, generated browser behavior, a network-request check, and an asynchronous-loading caveat.
Examples
Uses a jQuery 3.6.0 CDN URL, a local jQuery file, and `window.jQuery` as the test.
What you can do after
Apply it via ASP.NET Core script tag helpers and verify the fallback with browser developer tools.
How it connects
Connects script tag helpers with Razor layouts, content delivery networks, browser network requests, and JavaScript loading order.

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.