Reputation: 466
I know that merging CSS files can affect possitivly the performance of the Website but in my case I have the following scenario.
I have 4 color themes for my ASP.NET application
I wrote a bit of javascript that enables or disables stylesheets on the website
$("link[href='/Content/Style.css']").removeAttr('disabled');
$("link[href='/Content/Purple.css']").attr('disabled', 'disabled');
Works perferct when I am debugging the project locally.
The problem is when I publish to IIS.
Obviously IIS merges the CSS files in to one single file (see below) and my javascript does not work since it cannot find the CSS links.
<link href="/Content/styles?v=LJz1gcJyVEK_Atj5S7zoyR1lIdMwZ5IJIZn8ff329wQ1" rel="stylesheet">
Is there a way to say to IIS to not merge CSS files?
Or is do you have any better suggestion on how to implement this?
Upvotes: 0
Views: 273
Reputation: 78535
In your project, you should have an App_Start/Bundling.cs
file with something similar to this:
Bundle css = new StyleBundle("~/Content/styles");
css.IncludeDirectory("~/Content/", "*.css", true);
This takes all the CSS files from the content directory and bundles them into a single CSS file. Not only does this bundle the files together, but it also minifies them, so it's worth integrating your themes into this, something like:
string[] themes = { "Default", "Red", "Purple", "Green" };
foreach (var themeName in themes)
{
Bundle cssTheme = new StyleBundle("~/Theme/" + themeName);
cssTheme.Include("~/Theme/" + themeName + ".css");
bundleCollection.Add(cssTheme );
}
That will create one bundle for each one of your themes. Then, in your _Layout.cshtml
you can render the bundles like so:
@{
string[] themes = { "Default", "Red", "Purple", "Green" };
}
@Styles.Render(themes.Select(theme => "~/Theme" + theme).ToArray())
When this renders, you'll see the following HTML printed out:
<link href="/Theme/Default" rel="stylesheet" type="text/css">
<link href="/Theme/Red" rel="stylesheet" type="text/css">
<link href="/Theme/Purple" rel="stylesheet" type="text/css">
<link href="/Theme/Green" rel="stylesheet" type="text/css">
Allowing you to use your existing Javascript, like:
$("link[href^='/Theme/Default']").removeAttr('disabled');
$("link[href^='/Theme/Purple']").attr('disabled', 'disabled');
Note the use of the attribute starts with selector, as in production ASP.NET will append a unique querystring onto the end of your theme name
Upvotes: 2