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
1<?php
2namespace modules\user\assets;
3use yii\web\AssetBundle;
4/**
5* Class UserAsset
6* @package modules\user
7*/
8class UserAsset extends AssetBundle
9{
10/**
11* @inheritdoc
12*/
13public $sourcePath = '@app/modules/user/assets';
14/**
15* @inheritdoc
16*/
17public $js = [
18'js/user.js'
19];
20/**
21* @inheritdoc
22*/
23public $css = [
24'css/user.css'
25];
26/**
27* @inheritdoc
28*/
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 :

Plain text
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 :

PHP
1<?php
2namespace modules\user;
3use yii\base\Module;
4use modules\user\assets\UserAsset;
5use Yii;
6class UserModule extends Module
7{
8public function init()
9{
10parent::init();
11UserAsset::register(Yii::$app->view);
12}
13}