Hi I wanted to know the advantage of registering Asset Bundle following the process described in the docs like Process one in AppAsset.php
public $js = [
'js/myjsfile.js'
];
then in the view file adding Namespace like
namespace app\assets;
and then adding the use statement like
use app\assets\AppAsset;
AppAsset::register($this);
Instead of doing all this if I use Process Two
$this->registerJs('js/myjsfile.js', $this::POS_READY);
it works fine. So why should I use Process One.
Thanks.
Asset Bundles have some advantages over normal registering. Apart from what @deacs said in his/her answer here are others:
All the features that makes bundles shine are found in docs
One of the main reasons for using an Asset Bundle is that your assets' paths will always be correct. Consider:
$this->registerJsFile('js/myjsfile.js', ['position'=>$this::POS_READY]);
will generate something like:
<script src="js/myjsfile.js"></script>
Which works great for non urlManager enabled urls, e.g. http://localhost/yiiproject/index.php?r=user/update&id=8
because your browser looks for the js file at: /yiiproject/js/myjsfile.js
But if you enable urlManager, your url will look like http://localhost/yiiproject/user/update/8
, which means your browser will look for your js file at: /yiiproject/user/update/8/js/myjsfile.js
.
You could overcome this problem by using:
$this->registerJsFile(Yii::$app->request->baseUrl.'/js/myjsfile.js', ['position'=>$this::POS_READY]);
But the Asset Bundle basicly does that for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With