The following two scenarios provides a way to load JS and CSS files in the Yii application.
- Loading in a particular view file
- Loading for a complete module
For example, if a "user" module is created in your application as modules/user then follow the steps listed below
- Create a folder named as "assets" in module,
- Create two subfolders in "assets" as JS & CSS and include the files in the respective folders
- Create an asset file UserAsset.php which extends yii\web\AssetBundle class in the "assets" folder of module.
Declare the following in UserAsset.php
1<?php2namespace modules\user\assets;3use yii\web\AssetBundle;4/**5* Class UserAsset6* @package modules\user7*/8class UserAsset extends AssetBundle9{10/**11* @inheritdoc12*/13public $sourcePath = '@app/modules/user/assets';14/**15* @inheritdoc16*/17public $js = [18'js/user.js'19];20/**21* @inheritdoc22*/23public $css = [24'css/user.css'25];26/**27* @inheritdoc28*/29public $depends = [30'yii\web\JqueryAsset',31'yii\web\YiiAsset'32];33}
Load JS and CSS file in View File
To load the above included js and css files in a view file, we need to register UserAsset bundle. Declare the following in modules/user/views/user-management/_form.php :
1UserAsset::register($this);
Load JS and CSS file in a Module
To load above included js and css files in a module, we need to register UserAsset bundle at the time of module initialization. Declare the following in modules/user/UserModule.php :
1<?php2namespace modules\user;3use yii\base\Module;4use modules\user\assets\UserAsset;5use Yii;6class UserModule extends Module7{8public function init()9{10parent::init();11UserAsset::register(Yii::$app->view);12}13}



