Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 327
Ben Cook Avatar asked Feb 17 '17 20:02

Ben Cook


2 Answers

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.

like image 133
Alexandre Swioklo Avatar answered Nov 03 '22 09:11

Alexandre Swioklo


I tried this way in our ASP.NET MVC 5 project when CDN fails

@Scripts.RenderFormat("<script src='{0}' integrity='sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa' crossorigin='anonymous'></script>", "~/bundles/bootstrapJS")

And this will generate (inside developer tool),

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

And From this answer we found that there is bug if script is fail to load from CDN

So we add script manually inside the tag.

<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   <script>(window.jQuery) || document.write('<script src="/Scripts/jquery-1.12.4.min.js"><\/script>');</script>
</head>
<body></body>
</html>
like image 42
Sujay Avatar answered Nov 03 '22 10:11

Sujay