Reputation: 511
I registered a JavaScript file in AppAsset like this:
public $js = ['Index/top_menu.js']
Is it necessary to use registerJs
and registerJsFile
?
If yes where should I use them?
Upvotes: 2
Views: 1310
Reputation: 33548
Asset bundles is recommended way of working with CSS and Javascript assets in Yii2. There is complete guide in official docs for that.
Example of application asset bundle:
<?php
namespace app\assets;
use yii\web\AssetBundle;
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
Example of extension or specific functionality asset bundle:
<?php
namespace app\assets;
use yii\web\AssetBundle;
class FontAwesomeAsset extends AssetBundle
{
public $sourcePath = '@bower/font-awesome';
public $css = [
'css/font-awesome.min.css',
];
public $publishOptions = [
'only' => [
'fonts/',
'css/',
]
];
}
Then in view or layout you can register it like this:
use app\assets\AppAsset;
...
AppAsset:register($this);
Alternatives such as registerJs()
and registerJsFile()
can be used but not recommended. Some of the biggest disadvantages are:
registerJs()
- Javascript in PHP string without strong need is evil - no IDE / editor highlighting and autocomplete, mixing two different languages in one file.
registerJsFile()
- Code base becomes less organized. With this approach you think about including specific files in specific locations. With asset bundles you just use according asset containing all files, options, etc.
There are more advantages, and this was already discussed for example in this SO question.
Upvotes: 1