Wednesday, June 29, 2011

CClientScript positioning

CClientScript is useful for including css files and javscript files, while avoiding duplication.

Things to know:

1. Yii injects css files just above the <title> tag. So, if you want to always override some included yii style, put your <styles> or <link rel=stylesheets> AFTER the <title> tag, and it will get loaded after the yii styles.

2. I recommend putting all your <styles> and <link rel=stylsheets> in the <head> and all your <scripts> just before </body>. <scripts> are blocking, so your page will load faster if the <scripts> are at the bottom. use:

Yii::app()->getClientScript()->coreScriptPosition = CClientScript::POS_END;

3. if you want to include some inline javascript in a view, but make it load at the bottom, after say jquery, use the registerScript() method. To format your js nicely, you can use the Heredoc syntax:

/* load some formatted js into a php variable: */
$js = <<<EOF
var = 'some javascript here!';
    function() { return 'you can format it as you like, and include php $variables'; };
EOF;

/* write the script at the bottom of the document  */
Yii::app()->getClientScript()->registerScript("some id", $js, CClientScript::POS_END);

2 comments: