Is it possible to conditionally enable CSS?

I have ascx in which there is CSS. Perhaps this ascx may be added several times to the page. The CSS that it uses should only be included once.

  • Is it possible to conditionally enable CSS? If so, how?
  • Is this considered bad practice?
+6
source share
5 answers

I have ascx in which there is CSS ... Is this considered bad practice?

Yes. Your CSS rules should ideally be defined in a separate static css file that only loads once in the header of your main page. CSS in the body is not up to standard.

If you configure the correct caching rules in your static CSS files, this will significantly reduce the amount of data that you pull on the cable, because CSS rules should not be loaded again for each page load. If you want to include this file only in the header, if some dependent ASCX files are displayed, see Neal Fenwick 's answer .

Update

For some reason, Neil Fenwick seems to have deleted his answer. I hope he does not mind me reproducing it here:

Definitely YES, it's possible.

I would recommend looking at a library like ClientDependency to manage your CSS and JS applications and dependencies.

Good examples of how to include the data listed on the CodeLix ClientDependency page. Organizing CSS and JS dependencies is a good practice, so you can repeatedly state your requirement, but only exit the dependency once.

+5
source

ClientScriptManager can handle this by simply checking to see if any particular “script” has been added. Designed 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); } 
+1
source

You may be very interested in looking at Modernizr , which allows you to do many interesting tests and load different resources (for example, CSS) depending on the test result. For example, you can download rounded-images.css if the browser does not support border radius, etc.

0
source

Based on Neil, answer . We use Telerik ASP MVC extensions to control our JavaScript and CSS in ASP.NET MVC. This allows smart inclusion of JS and CSS (even with partial viewing), preventing duplication of files. It comes with other bells and sounds (e.g. file merging and compression).

This probably doesn't apply to your exact situation based on your post (raw ASP.NET), but I thought I mentioned this for ASP.NET MVC users who are looking for the same thing.

0
source

Put this at the top of the html.

 <pre> <!--[if gte IE 8]> <link rel="stylesheet" type="text/css" href="ie8-and-up.css" /> <![endif]--> </pre> 

For more information, go to: http://css-tricks.com/132-how-to-create-an-ie-only-stylesheet/ GTE means more.

Horrible practice. If this is not all that you do at your work, as this will create a large workload, as each css file may need to be changed in the future.

-2
source

Source: https://habr.com/ru/post/895613/


All Articles