Web Development – Why Avoid Dynamic Server-Side Generated CSS?

cssserver-sideweb-development

As server-side generated HTML is trivial (and it was the only way to make dynamic webpages before AJAX), server-side generated CSS is not. Actually, I've never seen it. There are CSS compilers, but they generate CSS files which can be used as static.

Technically, it requires no special libraries, the HTML style tag should reference to the PHP(/ASP/whatever) templater script instead of the static CSS file, and the script should send out CSS content-type header – that's all.

Does it have cache problems? I don't think so. The script should send out no-cache etc. headers. Is it problem for designers? No, they should edit the CSS template (as they edit the HTML template).

Why we don't use dynamic CSS generators? Or if there's any, please let me know.

Best Answer

The big reason why css is seldom generated dynamically (this is also true for javascript) is because they are good candidates for caching. CSS is a very flexible way to style your pages, with the right combination of classes, you can get all of the different parts of all of your different pages styled according to all sorts of cues all Without having to condition any of it in the CSS itself on what actually happens to be present on this pageview.

Simply because CSS doesn't need to be different per page leads to a very common practice of optimizing the cost of downloading it. Most sites cram all of the css for their whole site into a single download, so that parts that would apply to different page-views are present in only one downloaded file. With caching, your clients don't have to wait for it to download a second time. Maybe more importantly, you, as a content provider, don't have to pay the cost of uploading the content more than once; and you can even put the static css on a server that is better suited serving static content, which frees resources for actual dynamic content on your application servers.

This practice is so common, that many browsers just assume that the css is static; and are very reluctant to download CSS they already have; even if the users reloads the page. This special treatment applies only to CSS; other content types get reloaded as expected.

Related Topic