A content delivery network (CDN) distributes static assets so they can be served without every request reaching the application server. In an ASP.NET Core layout, a script or link element can point to a CDN URL while a tag helper arranges a local fallback. That matters because a CDN may be unavailable, and cached assets may lag behind an application deployment. section 26.4.1 section 26.4.2
Configure the fallback according to the asset type:
- JavaScript: set script src to the CDN URL, asp-fallback-src to a local file, and asp-fallback-test to an expression that is true when the library loaded. For jQuery, the test is window.jQuery. section 26.4.1
- CSS: set link href to the CDN URL and asp-fallback-href to a local stylesheet. Supply a class, property, and expected value for the load test; the Bootstrap example tests whether .btn has display: inline-block. section 26.4.2
A JavaScript fallback in a Razor layout
In Views/Shared/_SimpleLayout.cshtml, a script pointing to CDNJS jQuery 3.6.0 uses asp-fallback-src="/lib/jquery/jquery.min.js" and asp-fallback-test="window.jQuery". The generated HTML includes the CDN script followed by a test that writes a local script element if jQuery is absent. section 26.4.1
Listing 26.15 Using a CDN for CSS in the Views/Shared/_SimpleLayout.cshtml file
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.3/
css/bootstrap.min.css"
asp-fallback-href="/lib/bootstrap/css/bootstrap.min.css"
asp-fallback-test-class="btn"
asp-fallback-test-property="display"
asp-fallback-test-value="inline-block"
rel="stylesheet" />
</head>
<body>
<div class="m-2">
@RenderBody()
</div>
</body>
</html>
The complete layout listing shows the CDNJS Bootstrap URL, local CSS fallback, and all three attributes needed for its computed-style test. section 26.4.2
Fallback and cache busting solve different problems. Fallback handles an asset that did not load from the CDN. Cache busting addresses stale static files: asp-append-version adds a content-derived version query string to a local asset URL, changing it when the file changes. section 26.4.1 section 26.4.2



