How To Move All Javascripts So They Appear Before Closing Body Tag?

I’ve been trying to figure out how to do this for a while and am stumped. For some crazy reason, YII goes against best practices and tries to insert all this JS in the HEAD tags and throughout the body. I want all of the JS to appear right before the closing body tag.

I’m using my own jQuery (v.1.9.0), Bootstrap, etc. and have set the scriptMap settings to false. However, yiiactiveform is still being inserted in the HEAD tags and JS that is used in my views using enableClientValidation and also JS written at the bottom of my views is still showing up in the BODY.

How can this be changed?

Its not so much that it goes against best practices as the BEGIN position is the default. You can change it quite easily.

CClientScript is your friend. With CClientScript you can add your javascript code or source files anywhere you like. If you want them to be on every page I suggest that you add them where you want them in your master layout file (most likely called main.php in you layout directory). Here is a quick usage example to put in you view:

<?php Yii::app()->clientScript->registerScript('script-name',

    "document.write("Hello, world.", 



So, in the example you have the script name as the first argument, the script code as the second argument, and finally the script position as the third argument. Your choices for position are:






The POS_END option will get you what you want in this situation. You can experiment with them and find where the code is placed using each one.

If you would like to add a source file to your view instead you can do it with this:

<?php Yii::app()->clientScript->registerScriptFile('url/to/file', CClientScript::POS_HEAD); ?>

In this case the first argument is the location of the file and the second argument is the position where the <script> tag will be inserted.

Hope this helps.