Suture CSS or JavaScript Files to Reduce HTTP Requests

A server-side variation of merging CSS and JavaScript files before uploading to the server is to do this digital suturing at the server. You can “suture” CSS or JavaScript files together before delivery from the server to save HTTP requests. Often developers create separate style sheets and scripts for organizational purposes, and import them into their pages as needed. There are two problems with this approach:

it requires additional HTTP requests, and

you can encounter the same-domain connection limit.

Scripts that load in the head of your HTML document actually block the loading and parsing of other objects, until they are downloaded . You can have your organization and eat it too by combining style sheets or JavaScript files on demand to create one master file at the server with PHP or JSP. Done properly, these combined files can also be cached.

Here is how this digital surgery would work for CSS. You need to tell the server two things: first, to parse CSS files for PHP commands and second, to send the correct MIME type:

To deliver files based on browser environment variables (for example, to simulate an @import to filter out older browsers), you could use software like phpsniff available at Sourceforge phpsniff.

Caching Dynamic Files

As specified above, the dynamic CSS file will not cache properly. If you add the following headers to the top of your PHP file after the content type, they will cache for three hours (adjust 10,800 seconds as necessary).

Conclusion

This article shows how to “suture” or merge CSS or JavaScript files together at the server to avoid costly HTTP requests, while still maintaining separation of logically discrete styles or behavior. Suturing can be done automatically with PHP or JSP code at the server, or by merging files manually by developers to minimize HTTP requests to avoid the slight overhead of auto-suturing.

Further Reading

CSS + PHP: Organized and Optimized?

Explores the idea of suturing CSS files together with PHP. By Mike Papageorge of Fiftyfoureleven.