There are many methods that we can add javascript, css into your Yii App. Today I will demonstrate some simple and helpul methods.

A simple way to add js, css by editing config/main.php

// application components
  'components'=>array(
         // ...
        'clientScript'=>array(
            'packages'=>array(
                'jquery'=>array(
                    'baseUrl'=>'//ajax.googleapis.com/ajax/libs/jquery/1/',
                    'js'=>array('jquery.min.js'),
                )
            ),
        ),
        // ...
  ),

Using getClientScript

Usually, We add in block of code into Controller or layout of your theme

You can also add scripts from controller action. Just add this line in an action method then that script will apear only in that view:

$baseUrl = Yii::app()->baseUrl; 
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/js/yourscript.js');
$cs->registerCssFile($baseUrl.'/css/yourcss.css');

Or shorter:

Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/javascript/file',CClientScript::POS_END);
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/path/to/css/file');

Please notice the second parameter when you register the js file, it's the position of your script, when you set it CClientScript::POS_END, you let the HTML renders before the javascript is loaded.

Include core js files of framework like jquery.js, jquery.ui.js

Yii::app()->clientScript->registerCoreScript('jquery');     
Yii::app()->clientScript->registerCoreScript('jquery.ui');

Include Js, css all action

In protected/components/Controller.php, this class extends CController, we override action named "beforeAction" we declare what js, css that we want o add to site.

Examples:

public function beforeAction($action) {
    if( parent::beforeAction($action) ) {
        /* @var $cs CClientScript */
        $cs = Yii::app()->clientScript;
        /* @var $theme CTheme */
        $theme = Yii::app()->theme;
        $cs->registerPackage('jquery');
        $cs->registerPackage('history');
        $cs->registerScriptFile( $theme->getBaseUrl() . '/js/highlight.js' );
        $cs->registerScriptFile( $theme->getBaseUrl() . '/js/jquery.ba-dotimeout.min.js' );
        $cs->registerScriptFile( $theme->getBaseUrl() . '/js/jquery.scrollTo-1.4.3.1-min.js' );
        //$cs->registerScriptFile( $theme->getBaseUrl() . '/js/jquery.scrollTo-min.js' );
        $cs->registerScriptFile( $theme->getBaseUrl() . '/js/script.js' );
        $cs->registerCssFile($theme->getBaseUrl() . '/css/reset.css');
        $cs->registerCssFile($theme->getBaseUrl() . '/css/main.css');
        return true;
    }
    return false;
}

References

  • http://yii.codexamples.com/v1.1/CClientScript/
  • http://stackoverflow.com/questions/1998449/include-css-javascript-file-in-yii-framework