Yii2:注册资产包与注册外部 Js 文件 [英] Yii2: Registering Asset Bundle vs registering external Js file

查看:22
本文介绍了Yii2:注册资产包与注册外部 Js 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道按照文档中描述的过程注册 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.

  1. 对此的任何优势和原因将不胜感激.
  2. 如果我按照流程一是否需要将所有js文件添加到AppAsset.php 单独.
  1. Any advantage and reason for this will be greatly appreciated.
  2. 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 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆