[英]Yii2: Registering Asset Bundle vs registering external Js file
嗨,我想知道按照AppAsset.php中的Process one等文檔中描述的流程注冊Asset Bundle的優勢
public $js = [
'js/myjsfile.js'
];
然后在視圖文件中添加Namespace
namespace app\assets;
然后添加use語句
use app\assets\AppAsset;
AppAsset::register($this);
如果我使用Process Two,而不是完成所有這些
$this->registerJs('js/myjsfile.js', $this::POS_READY);
它工作正常。 那我為什么要使用Process One呢 ?
謝謝。
Asset Bundles比正常注冊有一些優勢。 除了@deacs在他/她的回答中所說的還有其他人:
所有使捆綁閃耀的功能都可以在docs中找到
使用資產包的主要原因之一是您的資產路徑始終是正確的。 考慮:
$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
因為您的瀏覽器在以下/yiiproject/js/myjsfile.js
查找js文件: /yiiproject/js/myjsfile.js
但是如果你啟用了urlManager,你的url將看起來像http://localhost/yiiproject/user/update/8
,這意味着你的瀏覽器將在以下位置查找你的js文件: /yiiproject/user/update/8/js/myjsfile.js
。
您可以使用以下方法克服此問題:
$this->registerJsFile(Yii::$app->request->baseUrl.'/js/myjsfile.js', ['position'=>$this::POS_READY]);
但是Asset Bundle基本上可以幫到你。
使用Asset Bundles,您還可以從'vendor'文件夾中獲取最新版本,因此如果您需要更新某些lib,則無需手動執行此操作,因為composer已經執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.