【问题标题】:Bundle JS files using CDN and integrity attribute使用 CDN 和完整性属性捆绑 JS 文件
【发布时间】:2021-05-02 20:56:29
【问题描述】:

在 ASP.NET MVC 5 中,是否可以使用 BundleColletion.UseCdn 并使用 HTML 完整性属性进行渲染?例如,有没有办法做到这一点:

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")
);

渲染成这样?

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

【问题讨论】:

  • 您找到解决方案了吗?我也面临同样的问题。

标签: asp.net-mvc-5 bundle cdn


【解决方案1】:

部分答案。

要添加 crossorigin="anonymous" 属性,您可以使用 @Scripts.RenderFormat

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

您也可以在 RenderFormat 中包含 integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" 部分,但它看起来不是一个好的解决方案。

【讨论】:

    【解决方案2】:

    当 CDN 失败时,我在我们的 ASP.NET MVC 5 项目中尝试过这种方式

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

    这将生成(在开发者工具中),

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

    this 的回答我们发现如果脚本无法从 CDN 加载存在错误

    所以我们在标签内手动添加脚本。

    <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>
    

    【讨论】:

      【解决方案3】:

      你可以拥有它

       <script src='@Scripts.Url("~/bundles/jquery")' crossorigin="anonymous" integrity="value"> </script>
      

      【讨论】:

        猜你喜欢
        • 2011-11-18
        • 1970-01-01
        • 2017-01-17
        • 2023-03-23
        • 1970-01-01
        • 2023-03-21
        • 2012-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多