A little while ago I wrote a post about how I manually combine/pack Javascript files. Even as I was writing it I was thinking “hey, this would be a great CakePHP plugin/component/helper. Before I could code it Brad Daily beat me to it. However there are a couple of things I didn’t like about his method, particularly the need for configuration files (how anti Cake!) and the need to run a console script to generated the packed versions.

My First Solution

Suitably inspired I whipped up my own version. And it was awesome. It was so friggen automagic that you didn’t even have to change your code. Just include the helper and it did the rest - assuming you were using the new (as in Cake 1.2) scripts_for_layout syntax and not adding your scripts inline.

The Snag

Unfortunately I had missed a small issue. Since the helper relied on the afterRender callback to do most of the work any js/css added in the layout was missed. See the afterRender is called after the view is rendered, but BEFORE the layout is rendered. Doh! Digging through the base helper I saw a promising callback, afterLayout. After a bit more digging I found that this is merely a placeholder (added sometime around new years) and isn’t actually called anywhere. I’m not sure if it would have worked in my case anyway, since I really needed something like duringLayoutHeaderRender callback.

My Second Solution

So I reworked the interface of the helper. It’s less automagic now, but works with scripts from both the layout and view. Basically instead of just echoing $scripts_for_layout you use the helper. Otherwise you still include JavaScript and CSS as normal, making sure to set inline to false. Full directions and an example are in the Sandbox as usual.

Pros and Cons

I like Brad’s helper better for certain projects. Particularly ones that uses a large amount of JavaScript, as his photo manager app does. But I think for most small sites, with just a few files the automatic approach works out better. Plus mine packs CSS files in addition to JS. This is probably a good time to mention that Brad’s app, SlideShowPro, is totally awesome. I recently used it when developing AndrewSaul.com. Basically I went from no photo gallery to full featured, cool looking, seamlessly integrated photo gallery in thirty minutes. Seriously, I was shocked when I read this was the product of just two guys working nights.

Bringing It Home

Checkout the helper. It’s kinda cool. The Sandbox jumped from a 64 to a 79 in YSlow after I applied it. I also included an .htaccess file that handles things like gzip, expire time and ETAGS. Unfortunately my host doesn’t support any of those, so I didn’t get any benefit from it.

Popularity: 78% [?]