Blog Archive

Saturday 4 August 2012

Caching assets in FUEL CMS

FUEL CMS has several enhancements in terms of classes over plain vanilla Codeigniter. One which I have recently been making more use of is the Asset class.

I’ve been using Andy Clarke’s 320 & Up and in the early version of this, there were a number of CSS and JS files, some conditional for IE.

The Asset class in FUEL CMS allows some neat optimisations regarding CSS & JS that are worth stressing. Typically you can use the css() method to do something simple like:

<?php echo css('base'); ?>

and this will create a <link> tag with an href to the (now cached) base.css file. However, if you have a conditional file for IE you can set the method like this:

<?php echo css('legacy-ie', NULL, 
  array('output' => TRUE, 'attrs' => 'media="screen"', 'ie_conditional' => 'lte IE 6')); ?>

and this will surround the tag with IE conditional comments, and add attributes as specified in the 'attrs' array key.

But there’s more! By combining several css file names as arguments to the css() method, the files can be combined by the Asset class, and with the ‘output’ key set to ‘gzip’, the resulting cache file will be gzipped too. Eg:

<?php echo css('base, home', NULL, array('output' => 'gzip')); ?>   

your server environment permitting of course!

Most of the functionality for the css() method is also available to the js() method too. Eg to combine Imgsizer & Selectivizr scripts and gzip them with IE conditional tags around them:

<?php 
echo js('imgsizer, selectivizr', NULL,
  array('output' => 'gzip', 'ie_conditional' => '(lt IE 9) & (!IEMobile) '));
 ?>

results in the following being rendered in a cached file:

<!--[if (lt IE 9) & (!IEMobile) ]>
<script src="/assets/cache/d370bce01d8e837e3253b2d90ac8c4fb_1325372400.php"
 type="text/javascript" charset="utf-8"></script>
<![endif]—>

If you want to, the ‘output’ array key value can simply be set to TRUE and this will not only gzip but will also clear out whitespace in the source files too. Consult the Asset class guide for more information.

No comments:

Post a Comment

My top artists