Search code examples
asp.net-mvcbundling-and-minification

Is it possible to bundle scripts and styles per page


Although bundling is a neat feature of VS, sometimes I want to have a script or css to be available to a particular page. This way, I can make sure that name conflicts and/or overrides will be avoided.

Is it possible to bundle files so that only global and page specific files are available?

So for example, say I have a page called Cabinet.cshtml. And I also have Cabinet.js and Cabinet.css files. On the other hand I have another page called AdminPanle.cshtml with files admin.js and admin.css.

Now, I would like these two views to have access only to their corresponding files and also jQuery and jQuery ui. So jQuery must be global.


Solution

  • So what's the problem? By default in your BundleConfig.cs you have:

    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));
    
    bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                        "~/Scripts/jquery-ui-{version}.js"));
    

    So put this bundles in your head of your _Layout.cshtml:

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
    

    And create 4 other bundles:

    //scripts
    bundles.Add(new ScriptBundle("~/bundles/cabinet").Include(
                        "~/Scripts/Cabinet.js"));
    bundles.Add(new ScriptBundle("~/bundles/admin").Include(
                        "~/Scripts/admin.js"));
    //styles
    bundles.Add(new StyleBundle("~/Content/cabinet").Include("~/Content/Cabinet.css"));
    bundles.Add(new StyleBundle("~/Content/admin").Include("~/Content/admin.css"));
    

    Now you can separate theese scripts and styles and add them only on page that you need.

    Also I suppose it's good to define 2 sections in your _Layout.cshtml in head tag.

    <head>
        //other scripts and styles here
        @RenderSection("scriptslib", required: false)
        @RenderSection("csslib", required: false)
    </head>
    

    So now in your Views (Cabinet.cshtml and AdminPanle.cshtml) you can place your libs where they suppose to be like this:

    @section scriptslib{
        @Scripts.Render("~/bundles/cabinet")
        }