问题描述
我想知道按照文档中描述的过程注册 Asset Bundle 的好处,例如流程一在 AppAsset.php 中
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 appassets;
然后添加像
use appassetsAppAsset;
AppAsset::register($this);
如果我使用流程二
$this->registerJs('js/myjsfile.js', $this::POS_READY);
它工作正常.那么我为什么要使用流程一.
it works fine. So why should I use Process One.
- 对此的任何优势和原因将不胜感激.
- 如果我按照流程一是否需要将所有js文件添加到AppAsset.php 单独.
- Any advantage and reason for this will be greatly appreciated.
- If I follow the process one Do I need to add all the js files in AppAsset.php individually.
谢谢.
推荐答案
使用 Asset Bundle 的主要原因之一是您的资产路径始终是正确的.考虑:
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]);
会产生类似的东西:
<script src="js/myjsfile.js"></script>
这对于非 urlManager 启用的 url 非常有用,例如http://localhost/yiiproject/index.php?r=user/update&id=8
因为您的浏览器会在以下位置查找 js 文件:/yiiproject/js/myjsfile.js代码>
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
但是如果你启用了 urlManager,你的 url 将看起来像 http://localhost/yiiproject/user/update/8
,这意味着你的浏览器会在以下位置寻找你的 js 文件:/yiiproject/user/update/8/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]);
但是 Asset Bundle 基本上可以为您做到这一点.
But the Asset Bundle basicly does that for you.
这篇关于Yii2:注册资产包与注册外部 Js 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!