In my last post we explored how to use the environment tag helper to generate different HTML for Development versus Production environments in ASP.NET MVC6. I very briefly touched on the link and script tag helpers. In this post, we will dig into the details of these very useful tag helpers.
The link and script tag helpers are intended to make it easier for us to add link and script tags to our HTML. In particular, these tag helpers simplify the process of referencing a large number of files in a development environment, referencing CDNs with local fallbacks and cache busting.
/scripts/*.js. This pattern, however, would not include any of the files in sub-directories. This is where globbing gets more interesting. We can include all JS files in a folder and all subfolders by specifying the pattern
We could include all the individual script files above using a single script tag helper as follows:
Which will generate the following HTML:
There is also src-exclude attribute if there were a set of files you wanted to exclude from the list. For example, to exclude the services scripts in the example above, we would use the following:
The link tag helper works in exactly the same way with the asp-href-include and asp-href-exclude attributes.
CDNs and Fallbacks
It is a common approach to reference popular frameworks from hosted CDN in order to reduce network load on your server and potentially improve performance for the end user. For popular frameworks like jQuery and Bootstrap, there is a good chance that the browser will already have a cached version of these files.
Referencing files from a CDN can be a bit of a pain because you also need to provide a fallback to a version of the file hosted on your servers. A fallback is necessary because you do not want your application to go down just because the CDN is not currently reachable.
The script and link tag helpers make it easier to specify a fallback test and file location. Here is a basic example for the popular Bootstrap framework:
<link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/css/bootstrap.min.css"
Which is infinitely cleaner than manually writing the following HTML that gets generated by the tag helpers:
<link rel="stylesheet" href="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/css/bootstrap.min.css" />
To enabling cache busting, just set the asp-append-version attribute to true.
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true"/>
Which will generate a link tag in HTML with a file version query parameter appended:
<link rel="stylesheet" href="/css/site.min.css?v=UdxKHVNJA5vb1EsG9O9uURFDfEE3j1E3DgwL6NiDGMc" />
The process is identical for the script tag helper.
The new link and script tag helpers make the process of including multiple files, referencing CDN hosted resources and cache busting extremely simple.
August 29, 2015 – Updated to align with new renamed attributes in Beta 6 and newer