简体   繁体   中英

Add Javascript to header section of an ASP.NET/MVC web page from a view with bundling?

If found this Stack Overflow page that shows you how to add a Javascript include to an ASP.NET/MVC (Razor) view, so that it ends up in the HEAD section of the web page:

Add CSS or JavaScript files to layout head from views or partial views

It works great. But I'm wondering if there is a way to do it in a way that takes advantage of bundling? I found this SO post that says it isn't possible and to use something called Cassette, but it's from 2012 so I'm wondering if there's a way to do it now native to ASP.NET/MVC/Razor:

MVC Bundles: How to add assets in views and have them render combined with the main layout page bundle

I found this SO post that talks about adding new bundles dynamically but it appears to add them only to the BODY section, not the HEAD:

MVC Bundles: How to add assets in views and have them render combined with the main layout page bundle

Your comment has helped me understand what you want to do now. As far as rendering out bundles from a view, it works the same way the answer to your first question.

First, make a bundle for those file(s) that you want.

BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/mySpecialBundle").Include(
                      "~/Scripts/notOftenUsedScript.js",
                      "~/Scripts/someOtherScript.js"));

Next, in your layout, define a section where you want to be able to render out the JavaScript bundle.

_layout.cshtml

@RenderSection("scripts", required: false)

Now, in any view that you want to render the special bundle, reference this section and use the same syntax that you would in the layout page for bundle rendering.

ExampleView.cshtml

@section scripts{
    <!---Test section rendering-->
    @Scripts.Render("~/bundles/mySpecialBundle")
}

The @Scripts.Render and @Styles.Render will work from any razor page in your application. Using the section allows us to control where the output from our view page will land in the master page.

With that said, if the JS is truly lightweight, then after the first time your user hits a page with the special bundle, it should be cached by their browser. So, the performance hit from just having this in your layout all the time would probably be minimal the first page hit and non-existent for each page hit afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM