Jorgeska Jorgeska - 1 month ago 8
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

views/usuario/js/create.js
that it's only going to be used in one view
views/usuario/create.php
.

I'd prefer not to use ...

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


... in
assets/AppAsset.php
in order to mantain loading of scripts at the end of the page.

create.js
it's only needed in the
create.php
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 '<'
http://www.example.com/usuario/js/create.js
Line 1


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

$this->registerJsFile('js/create.js');


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

Any help would be appreciated.

Answer

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().