Script Tag Helper in ASP.NET Core

By Rick Anderson

The Script Tag Helper generates a link to a primary or fall back script file. Typically the primary script file is on a Content Delivery Network (CDN).

A CDN:

  • Provides several performance advantages vs hosting the asset with the web app.
  • Should not be relied on as the only source for the asset. CDNs are not always available, therefore a reliable fallback should be used. Typically the fallback is the site hosting the web app.

The Script Tag Helper allows you to specify a CDN for the script file and a fallback when the CDN is not available. The Script Tag Helper provides the performance advantage of a CDN with the robustness of local hosting.

The following Razor markup shows the script element of a layout file created with the ASP.NET Core web app template:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
        asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
        asp-fallback-test="window.jQuery"
        crossorigin="anonymous"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
</script>

The following is similar to the rendered HTML from the preceding code (in a non-Development environment):

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
        crossorigin="anonymous"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=">
</script>
<script>  (window.jQuery || document.write(
        "\u003Cscript src=\u0022\/lib\/jquery\/dist\/jquery.min.js\u0022 " +
        "crossorigin =\u0022anonymous\u0022 integrity =\u0022sha256 - " +
        "FgpCb\/KJQ32o\/NM<snip>u8=\u0022\u003E\u003C\/script\u003E"));
</script>


In the preceding code, the Script Tag Helper generated the second script ( <script> (window.jQuery || document.write() element, which tests for window.jQuery. If window.jQuery is not found, document.write( runs and creates a script

Commonly used Script Tag Helper attributes

See Script Tag Helper for all the Script Tag Helper attributes, properties, and methods.

href

Preferred address of the linked resource. The address is passed thought to the generated HTML in all cases.

asp-fallback-href

The URL of a CSS stylesheet to fallback to in the case the primary URL fails.

asp-fallback-test-class

The class name defined in the stylesheet to use for the fallback test. For more information, see FallbackTestClass.

asp-fallback-test-property

The CSS property name to use for the fallback test. For more information, see FallbackTestProperty.

asp-fallback-test-value

The CSS property value to use for the fallback test. For more information, see FallbackTestValue.

asp-fallback-test-value

The CSS property value to use for the fallback test. For more information, see FallbackTestValue

Additional resources