Yii2: Include View Specific JavaScript

To include JavaScript for specific action, either the JavaScript code or file is to be registered in view file.

Method 1: Register JavaScript File

Use registerJsFile().

$this->registerJsFile('@web/js/file.js', [
    'position' => View::POS_END,
]);

Note: optional position. values: POS_HEAD, POS_BEGIN, POS_END.

If order of the file is to be placed after some set of files, for example, css and js files defined in SomeAsset:

use frontend\assets\SomeAsset;
$this->registerJsFile('@web/js/file.js', [
    'depends' => SomeAsset::className(),
]);

Method 2: Register Javascript Code

Use registerJs().

$this->registerJs('console.log("hello world");', View::POS_END);

Position is optional. Possible values for the position where the script will be inserted to are: POS_READY (default), POS_HEAD, POS_BEGIN, POS_END, POS_LOAD..

If you have multiple lines of codes, it’s neater to assign the code to variable and register the variable:

$js = <<< 'SCRIPT'
 /*
  * JavaScript code here
  */ 
SCRIPT; 
$this->registerJs($js, View::POS_END);

Leave a Reply

Your email address will not be published. Required fields are marked *