ASP.NET MVC4 how to create bundle with js and css together in one rule?

Edi Wang picture Edi Wang · Nov 24, 2012 · Viewed 7.3k times · Source

I have a superfish jquery plugin, which has 4 js and 1 css:

<script src="~/Scripts/JQ_Addons/SuperFish/jquery.bgiframe.min.js"></script>
<script src="~/Scripts/JQ_Addons/SuperFish/hoverIntent.js"></script>
<script src="~/Scripts/JQ_Addons/SuperFish/supersubs.js"></script>
<script src="~/Scripts/JQ_Addons/SuperFish/superfish.js"></script>
<link href="~/Scripts/JQ_Addons/SuperFish/superfish.css" rel="stylesheet" />

I want to create one bundle for all of this, but when I call bundles.Add(), it can only add one type of bundle, ScriptBundle or StyleBundle.

bundles.Add(new ScriptBundle("~/bundles/superfish").Include(
            "~/Scripts/JQ_Addons/SuperFish/jquery.bgiframe.min.js",
            "~/Scripts/JQ_Addons/SuperFish/hoverIntent.js",
            "~/Scripts/JQ_Addons/SuperFish/supersubs.js",
            "~/Scripts/JQ_Addons/SuperFish/superfish.js")); // I can not add css here

and in the view, I can only choose to render one type of bundle:

@Styles.Render or @Script.Render

So, my question is: Is it possible to create only one bundle rule with both js and css included? and in my view, I want something like:

@Bundles.Render("~/bundles/superfish")

Answer

photo_tom picture photo_tom · Nov 24, 2012

The main reason you cannot has to do with how browser handle these files.

  • To retrieve style sheets, the html tag is <link>
  • To retrieve scripts, the html tag is <script>

The html tag tells the browser what the contents of the file is.

On the MVC server side code, the main reason to use bundling is to combine script and link files into a single file. Then to minimize them. Bundling uses different minimization functions based on type of file. If you combine scripts and css into a single file, the bundling code will not properly minimize the resulting file.