Posted on 18/11/06 by Felix Geisendörfer
The authors of this post have marked it as deprecated. This means the information displayed is most likely outdated, inaccurate, boring or a combination of all three.
Policy: We never delete deprecated posts, but they are not listed in our categories or show up in the search anymore.
Ok, this won't be a ground breaking post. If you are using some JS in your application you know that those libraries can add up rather quickely. However, most people hate to load hundreds of KB in JS toys when coming to your page. It's too much. Therefor it's a smart idea to only include the JS that's really needed. In CakePHP this often directly related to the Controller/action that is running.
I'm fairly sure most people have run into this problem before. I'm also sure those people have figured out a way to solve the problem. Nevertheless, here comes my current approach on dynamically selecting which JS scripts to include on a certain page.
My solution simply adds 2 function and a member variable to the AppController ands looks like this:
var $jsIncludes = array('jquery/jquery');
if (!in_array($jsPath, $this->jsIncludes))
$this->jsIncludes = $jsPath;
$arrayPos = array_search($jsPath, $this->jsIncludes);
array_splice($this->jsIncludes, $arrayPos, 1);
So by setting a value for var $jsIncludes you can define your default includes that you always want to have included. Then you can use the includeJs/excludeJs function inside controller actions (or filters) to fine grain what libs you want to include. For example in my MenuEntriesController I have a beforeRender that looks like this:
var $name = "MenuEntries";
var $uses = array('MenuEntry', 'Menu');
And now the missing piece, the integration in your default.thtml layout:
By putting this little loop into yoursection, all JS libs will automatically get included. And even better, when DEBUG is set to a value bigger then 0, adding a unique hash to the include path will make sure your JS will never be cached.
So if up to now you've always included all JS for every page load, this might help to reduce bandwidth usage for both you, and the users of your application. I know this is not the most advanced solution one could come up with. I thought about using my light weight ACL algorithm for the problem. But then I decided that it's too simple a problem for that kind of bloat.
Btw. there is also a HeadHelper created by RosSoft that will allow you to include JS/CSS on a per view basis. However, most of my JS is included on a per Controller basis, so I created my own approach.
-- Felix Geisendörfer aka the_undefined
You can skip to the end and add a comment.
This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.