Prevent Browser Caching of Telerik CSS and JavaScript Files
Environment
Product | UI for Blazor |
Description
This KB article answers the following questions:
- How to prevent browser caching issues with the Telerik CSS theme and JSInterop (JavaScript) file when using static assets from the Telerik NuGet packages?
- How to implement a version-dependent cache buster for the
all.css
andtelerik-blazor.js
files? - How to disable the browser cache for Telerik client assets when upgrading the Telerik UI for Blazor components?
Solution
To avoid browser caching issues when upgrading the Telerik UI for Blazor version, use the so-called cache busting. Add the components' version number to the Telerik client asset URLs as a query string. In this way, the browser will always load the correct version of the CSS stylesheet and the JSInterop file. Browsers will still use cached Telerik client assets as long as the components version stays the same.
Using the correct client assets avoids Telerik-related JavaScript errors.
The required approach varies, depending on the Blazor application:
Normally, there is no need for cache busting when using the Telerik CDN, because the client asset URLs are unique for every Telerik UI for Blazor version.
Blazor Web Apps and Legacy Blazor Server Apps
You can use reflection to get the Telerik UI for Blazor version at runtime.
- Pick a type (class) from the Telerik UI for Blazor product. A good candidate is a component that exists in both old and new product versions, such as the
TelerikRootComponent
. - Get the component type with
typeof(TelerikRootComponent)
. You may need to usetypeof(Telerik.Blazor.Components.TelerikRootComponent)
if:- The
Telerik.Blazor.Components
namespace is not registered in_Imports.razor
as it should. - The Telerik CSS and JS assets are placed in a
.cshtml
file instead ofApp.razor
, for example, in legacy Blazor apps.
- The
- Use the
Assembly.GetName()
method and theAssemblyName.Version
property to extract the Telerik UI for Blazor version.
@{ var telerikUiForBlazorVersion = typeof(TelerikRootComponent).Assembly.GetName().Version; }
<link href="_content/Telerik.UI.for.Blazor/css/kendo-theme-default/all.css?@telerikUiForBlazorVersion" rel="stylesheet" />
<script src="_content/Telerik.UI.for.Blazor/js/telerik-blazor.js?@telerikUiForBlazorVersion"></script>
Standalone Blazor WebAssembly Apps and Hybrid Apps
If the Telerik CSS theme and JavaScript file reside in the index.html
file, you can hard-code the Telerik UI for Blazor version. In this case, it is crucial to update the query string manually every time when upgrading.
<link href="_content/Telerik.UI.for.Blazor/css/kendo-theme-default/all.css?7.0.0" rel="stylesheet" />
<script src="_content/Telerik.UI.for.Blazor/js/telerik-blazor.js?7.0.0"></script>
Notes
In addition to cache busting, you can use a defer
attribute to load the telerik-blazor.js
file asynchronously and improve the client-side app performance.