I've been having a hard time trying to figure out how to load jQuery
or other CORE scripts in Yii 2
.
In Yii 1
it seemed this was the way:
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
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"); ?>
produces this error:
Getting unknown property: yii\web\Application::clientScript
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'); ?>
Whilst this loads jQuery in the head, a second version of jQuery is also loaded by Yii when needed and hence causes conflict errors.
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.
How can I load jQuery and other core files without Yii loading duplicate copies of them when it needs them?
In order to disable
Yii2
's default assets you can refer to this question:Yii2 disable Bootstrap Js, JQuery and CSS
Anyway,
Yii2
's asset management way is different fromYii 1.x.x
. First you need to create anAssetBundle
. As official guide example, create an asset bundle like below in ``:Then, to publish them on your views:
Which
$this
refers to current view object.On the other hand, if you need to only register
JS
files into a view, you may use:yii\web\View::registerJsFile()
And if you need to only register
CSS
files into a view, you may use:yii\web\View::registerCssFile()
You can remove the core jQuery from loading like so:
config/web.php