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
<?php
namespace modules\user\assets;
use yii\web\AssetBundle;
/**
* Class UserAsset
* @package modules\user
*/
class UserAsset extends AssetBundle
{
/**
* @inheritdoc
*/
public $sourcePath = ‘@app/modules/user/assets’;
/**
* @inheritdoc
*/
public $js = [
‘js/user.js’
];
/**
* @inheritdoc
*/
public $css = [
‘css/user.css’
];
/**
* @inheritdoc
*/
public $depends = [
‘yii\web\JqueryAsset’,
‘yii\web\YiiAsset’
];
}
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 :
UserAsset::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 :
<?php
namespace modules\user;
use yii\base\Module;
use modules\user\assets\UserAsset;
use Yii;
class UserModule extends Module
{
public function init()
{
parent::init();
UserAsset::register(Yii::$app->view);
}
}