在 Yii 2 中加载 jQuery 等核心脚本

2022-01-04 00:00:00 jquery php yii2 yii

我一直很难弄清楚如何在 Yii 2 中加载 jQuery 或其他 CORE 脚本.

I've been having a hard time trying to figure out how to load jQuery or other CORE scripts in Yii 2.

Yii 1 中似乎是这样:

<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>

在 Yii 2 中,$app 是 Yii 的一个属性,而不是一个方法,所以上面的自然是行不通的,而是改成:

In Yii 2, $app is a property of Yii, not a method, so the above naturally doesn't work, but changing it to:

<?php Yii::$app->clientScript->registerCoreScript("jquery"); ?>

产生这个错误:

Getting unknown property: yiiwebApplication::clientScript

我找不到有关加载核心脚本的 Yii 2 的任何文档,因此我尝试了以下操作:

I couldn't find any documentation for Yii 2 about loading core scripts, so I tried the below:

<?php $this->registerJsFile(Yii::$app->request->baseUrl . '/js/jquery.min.js', array('position' => $this::POS_HEAD), 'jquery'); ?>

虽然这会在头部加载 jQuery,但 Yii 在需要时也会加载第二个版本的 jQuery,因此会导致冲突错误.

Whilst this loads jQuery in the head, a second version of jQuery is also loaded by Yii when needed and hence causes conflict errors.

此外,我不想使用 Yii 的 jQuery 实现,我更愿意维护自己的实现,因此这就是我这样做的原因.

Additionally, I don't want to use Yii's implementation of jQuery, I would prefer to maintain my own and hence that is why I am doing this.

我如何加载 jQuery 和其他核心文件而不需要 Yii 在需要时加载它们的重复副本?

How can I load jQuery and other core files without Yii loading duplicate copies of them when it needs them?

推荐答案

为了禁用 Yii2 的默认资产可以参考这个问题:

In order to disable Yii2's default assets you can refer to this question:

Yii2 禁用 Bootstrap Js、JQuery 和 CSS

无论如何,Yii2 的资产管理方式与Yii 1.x.x 不同.首先,您需要创建一个 AssetBundle.作为官方指南示例,在``:

Anyway, Yii2's asset management way is different from Yii 1.x.x. First you need to create an AssetBundle. As official guide example, create an asset bundle like below in ``:

namespace appassetsYourAssetBundleName;
use yiiwebAssetBundle;

class YourAssetBundleName extends AssetBundle 
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [ 
    'path/file.css',//or files 
]; 
public $js=[
     'path/file.js' //or files
];

//if this asset depends on other assets you may populate below array
public $depends = [
];
}

然后,根据您的观点发布它们:

Then, to publish them on your views:

use appassetsYourAssetBundleName;
YourAssetBundleName::register($this);

哪个 $this 引用当前视图对象.

Which $this refers to current view object.

另一方面,如果您只需要将 JS 文件注册到视图中,您可以使用:

On the other hand, if you need to only register JS files into a view, you may use:

$this->registerJsFile('path/to/file.js');

yiiwebView::registerJsFile()

如果您只需要将 CSS 文件注册到视图中,您可以使用:

And if you need to only register CSS files into a view, you may use:

$this->registerCssFile('path/to/file.css');

yiiwebView::registerCssFile()

相关文章