Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining CSS in a single request

Tags:

css

php

Does anyone know how to achieve something like TypeKit when combining multiple CSS request? Maybe I'am not aware of that but when you list some fonts the site would generate (maybe dynamic) CSS like 567,568,569.css lo load the font-file. I thought of it as dynamic as it would change if you use other combination (in this case font ID).

like image 943
Habib Rosyad Avatar asked Nov 25 '10 14:11

Habib Rosyad


People also ask

How do I combine multiple CSS files into one?

To combine external CSS files, you can simply copy / paste all of your CSS code into one main file. Therefore all of the content from within the other CSS files will now reside within the main file allowing the browser to only make one request for a CSS file instead of multiple.

Should you combine CSS files?

Combining CSS/JS files reduces the number of page requests, in turn reducing the number of round trips made to your server so that other resources can be retrieved faster. With HTTP/2, this is less of an issue as the protocol allows multiplexing, which allows requests and responses to be processed in parallel.

How to combine JS and CSS?

No, you can't combine js and css into one file.

How do I combine CSS in WordPress?

You can download it from the WordPress repository or by searching for it within your WordPress dashboard under “Add New” plugins. Once installed you will want to go into the settings and enable the “Optimize CSS Code” option. This will concatenate (combine) your CSS files.


1 Answers

I use the technique described by Carpetsmoker, but I didn't like the fact that the PHP script is invoked every time. On Apache, you can set the following rewrite rule (in .htaccess):

RewriteCond %{REQUEST_URI} ^/css/cache
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^css/cache/(.*)$ /css/csscacher.php?files=$1 [L]

So say a request comes in for /css/cache/file1.css-file2.css, Apache will test for its existence. If it doesn't exist, the request will be forwarded to the csscacher.php script with the filename passed as the value of the "files" param. csscacher.php will load and combine the multiple files, send the result to the browser, but also write the result to /css/cache/file1.css-file2.css. All subsequent requests will be served as a static file.

To clear the cache, you'd just delete everything in the /css/cache folder. csscacher.php will recreate them from the source files as requests come in. More detail here.

like image 182
Spektr Avatar answered Oct 06 '22 12:10

Spektr