Reputation: 85056
I have an ascx that has some CSS in it. It is possible that this ascx could be added multiple times to a page. The CSS that it uses would only need to be included once.
Upvotes: 6
Views: 1634
Reputation: 156524
I have an ascx that has some CSS in it... Is this considered bad practice?
Yes. Your CSS rules should ideally be defined in a separate, static css file that gets loaded only once in the header by your master page. CSS in the body is not standards compliant.
If you set up good caching rules on your static CSS files, this will significantly reduce the amount of data you pull across the wire because the CSS rules won't need to be loaded again for each page load. If you want to only include this file in the header if certain dependent ASCX files get rendered, look at Neil Fenwick's answer.
For whatever reason, Neil Fenwick seems to have deleted his answer. Hopefully he won't mind my reproducing it here:
Definitely YES, it is possible.
I would recommend looking at a library like ClientDependency to manage your CSS and JS includes & dependencies.
Good examples for how to include given on ClientDependency codeplex page. Its good practice to organise your CSS and JS dependencies so that you can assert their requirement multiple times, but only emit the dependency in the output once.
Upvotes: 5
Reputation: 6646
Building on Neil's answer. We make use of Telerik's ASP MVC extensions to manage our JavaScript and CSS in ASP.NET MVC. It allows for "smart" inclusion of JS and CSS (even from a partial-view) preventing file duplication. It comes with other bells-and-whistles as well (like file merging and compression).
This is probably not applicable to your exact situation based on your post (raw ASP.NET), but thought I would mention it for the sake of ASP.NET MVC users looking for the same thing.
Upvotes: 0
Reputation: 24918
The ClientScriptManager
can handle this simply by checking whether or not some particular "script" has been added. Intended for javascript, but works for anything.
if(!Page.ClientScript.IsStartupScriptRegistered("mykey")) {
Page.ClientScript.RegisterStartupScript(this.GetType(), "mykey", "<link type=\"text/css\" href=\"stylesheet.css\"/>", false);
}
Upvotes: 1
Reputation: 3236
Put that in the head of the html.
<pre>
<!--[if gte IE 8]>
<link rel="stylesheet" type="text/css" href="ie8-and-up.css" /> <![endif]-->
</pre>
For more info go to: http://css-tricks.com/132-how-to-create-an-ie-only-stylesheet/ GTE means greater than.
Horrible practice. Unless that is all you do at your work since that is going to create a big workload since each css file might need to be changed in the future.
Upvotes: -2
Reputation: 7693
You might be very interested in looking into Modernizr which allows you to do plenty of interesting test and load different resources (for example CSS) depending on test result. For example you might want to load rounded-images.css if the browser does not support border-radius etc.
Upvotes: 0