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
         // ...
        // ...

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();

Or shorter:


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


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.


public function beforeAction($action) {
    if( parent::beforeAction($action) ) {
        /* @var $cs CClientScript */
        $cs = Yii::app()->clientScript;
        /* @var $theme CTheme */
        $theme = Yii::app()->theme;
        $cs->registerScriptFile( $theme->getBaseUrl() . '/js/highlight.js' );
        $cs->registerScriptFile( $theme->getBaseUrl() . '/js/' );
        $cs->registerScriptFile( $theme->getBaseUrl() . '/js/jquery.scrollTo-' );
        //$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;