I would recommend you to take a look on this Autoload Plugin written by this marvelous guy ... oops, by me :).
So, using it you can easily split your javascript and even CSS into separate directories and you will have separate files included on each controller.
If you want to follow the trend - use RequireJS which give you ability to modularize your code and include only those pieces which you needed.
Although Autoload is my creation, I switched to RequireJS and I am quite happy with the results.
I will explain my approach with RequireJS.
What you need is the following code in the head section of your layout:
<script>
<?php if(is_file(
__DIR__.'/../../webroot/js/action/'.
$this->request->params['controller'].'/'.
$this->request->params['action'].'.js'
)){ ?>
var rPath = root+'js/app/action/<?php echo
$this->request->params['controller'].'/'.
$this->request->params['action']; ?>';
<?php } ?>
</script>
At the bottom of layout you need to include the requirejs file:
<script
data-main="<?php echo $this->Html->url('/'); ?>js/app"
src="<?php echo $this->Html->url('/'); ?>js/libs/requirejs.js">
</script>
The first piece just check if there is file for that specific controller and action in the folder like:
/wwwroot/js/actions/Posts/write.js
and if so, add a the var rPath which contain reference to that file.
Here is the example of RequireJS config file which I am using:
require.config({
baseUrl: root+'js/',
paths: {
jquery : 'libs/jquery.min',
//...your convenient shortcuts
}
});
//That's where the magic happen
if(typeof(rPath) !== 'undefined'){
requirejs([rPath]);
}
Finally if you need some javascript in your controller Posts and your action write you need to create a file in:
/wwwroot/js/app/Posts/write.js with the following content:
define([
'jquery', //reference to jquery
'app/Posts/controller' //module which you wrote for controller specific functions.
//other libs or modules if needed.
], function($){
//your functions for wirite action
});
Take a look on RequireJS documentation for more information.
Hope that helps.