Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to conditionally include CSS?

Tags:

html

css

asp.net

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.

  1. Is it possible to conditionally include CSS? If so how?
  2. Is this considered bad practice?
like image 753
Abe Miessler Avatar asked Aug 22 '11 16:08

Abe Miessler


1 Answers

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.

Update

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.

like image 190
StriplingWarrior Avatar answered Oct 27 '22 00:10

StriplingWarrior