How do I add type=“text/javascript” to a script tag when using System.Web.Optimization

让人想犯罪 __ 提交于 2019-12-29 06:51:29

问题


I have the following

bundles.Add(new ScriptBundle("~/bundles/scripts/common").Include(
                  "~/Scripts/jquery.validationEngine.js",
                  "~/Scripts/common.js"));

Which generates

<script src="/bundles/scripts/common?v=9O0Yi3fV_GWpGyJQ_QYURiOYy6SEmxUQtkUVN4GXo2U1"></script>

When rendered with

    <asp:PlaceHolder ID="PlaceHolderJs" runat="server">                
            <%: Scripts.Render("~/bundles/scripts/common") %>
    </asp:PlaceHolder>

Which is not valid HTML as its missing type="text/javascript". How do I make the BundleCollection output this element in the script tag?


回答1:


One way is to change how you render your scripts:

From:

@Scripts.Render("~/bundles/scripts/common")

To:

<script src="@BundleTable.Bundles.ResolveBundleUrl("~/bundles/scripts/common")" type="text/javascript"></script>

Or depending on how you are implementing bundling, you may need:

<script src="@Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/scripts/common")" type="text/javascript"></script>

Or for web forms:

<script src="<%= Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/bundles/scripts/common")%>" type="text/javascript"></script>

Although if there is a way to do it using @Script.Render I'd like to see it.

UPDATE: in response to your comments, as specified in this SO answer, in the pre-release version of System.Web.Optimization, there is an option called RenderFormat that will let you do this as well... but I think the stuff above is easier to read for this particular case.




回答2:


I believe the answer marked is not correct for type="text/css", it is correct for JavaScript (maybe the question title is misleading?). For CSS files you should use

@Styles.Render("~/bundles/styles/common")

and not @Scripts.Render(...). The reason is that minification is done, and only @Styles.Render(...) knows about Cascading Stylesheet syntax, @Scripts.Render(...) is specialized for JavaScript minification.



来源:https://stackoverflow.com/questions/15662096/how-do-i-add-type-text-javascript-to-a-script-tag-when-using-system-web-optimi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!