Setting up an environment for small websites is pretty easy. Mostly everyone evolved his own way of structuring assets, stylesheet, javascript and serversided scripts. There’s no need of splitting CSS or JS into a quadrillion of files, due it causes unnecessary requests to your server.
That works until complexity makes it impossible to keep track over your files. You may remember situations where you find yourself in the middle of searching inclusion-points, opening and closing css/js-files for the right line, etc.
The solution is: A good folderstructure combined with a central algorithm which determines the inclusion of CSS/JS on every page. Few weeks ago, I stumbled over Felix Geisendörfer’s “33 lines of magic – a lightweight approach to ACL”. That gave me the idea of using ACL for inclusion-control. I touched his source code slightly and wrote a small helper for cakePHP. However, it should be possible to adjust it to as many frameworks as there are out there.
It’s time saving to define a logic of auto-inclusion. In case of a MVC-Framework, it makes much sense to implement that on the controllers/actions in the form:
You can switch that behaviour on by defining two config-item:
/* * AUTOINCLUDING JS/CSS */ $config['Include.auto.css'] = true; $config['Include.auto.js'] = true;
Now that the url-driven files are included, let’s focus on files, that are needed across several controllers and actions. Thanks to the slightly adjusted ACL, it’s possible to define rules for them. Our rules are a set of commaseparated controller:action for every page, we want to include it. Plus: We can use the star-operator as a wildcard.
The ruleset will look like:
/* * CSS INCLUDING RULES */ $config['Include.css'] = array( 'admin.css' => '*:admin_*,admins:*', 'page.css' => 'start:*' ); /* * JAVASCRIPT INCLUDING RULES */ $config['Include.js'] = array( 'libraries/jquery-1.4.1.min.js' => '*:*', 'admin.js' => '*:admin_*,admins:*' );
As a matter of fact, the helper reduces erroneous request. It does so by checking whether the file exists, before including it. Files that do not exist, won’t be
included (!).
Now simply run it in your view like this:
<head> [...] <=$inclusion->css() ?> <=$inclusion->js() ?> </head>
Hope you enjoyed reading and have a DRY inclusion-life :) Download it here: Auto-Inclusion Helper for CSS/JS
No Comments