Jorgeska Jorgeska - 3 months ago 13
Javascript Question

Adding jQuery script to a single view in Yii2

I am working on the basic template of Yii2. I have got a jQuery script

that it's only going to be used in one view

I'd prefer not to use ...

public $jsOptions = array(
'position' => \yii\web\View::POS_HEAD

... in
in order to mantain loading of scripts at the end of the page.

it's only needed in the
view so I'd prefer to load it just for the create.php view.

So I've tried unsuccessfuly to follow ippi's instructions
Firebug keeps throwing me this error:

SyntaxError: expected expression, got '<'
Line 1

I guess there could be a problem with the route param of ...


... but I can't find it out.

Any help would be appreciated.


registerJsFile() needs an url, you should simply publish (make it web accessible) your file before registering it, e.g. :

$pub = Yii::$app->assetManager->publish(__DIR__ . '/create.js');
$this->registerJsFile($pub[1], ['depends' => ['yii\web\JqueryAsset']]);

Or you could create an asset bundle and registering it in your view.

Read more about publish() and registerJsFile().