Search code examples
asp.net-mvc-5bundlecdn

Bundle JS files using CDN and integrity attribute


In ASP.NET MVC 5, is it possible to use BundleColletion.UseCdn and have it render with the HTML integrity attribute? For example, is there someway to make this:

bundles.UseCdn = true;
bundles.Add(
    new ScriptBundle("~/bundles/jquery", "https://code.jquery.com/jquery-3.1.1.min.js")
        .Include("~/Scripts/js/jquery/jquery-3.1.1.min.js")
);

render as this?

<script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>

Solution

  • Partial answer.

    To add crossorigin="anonymous" attribute you can use @Scripts.RenderFormat

    @Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\" crossorigin=\"anonymous\"></script>", "~/bundles/jquery")
    

    You also can include integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" part in RenderFormat, but it does not look like a good solution.