Downloading basic scripts like jQuery in Yii 2

It was hard for me to find a way to load jQuery or other CORE scripts in Yii 2 .

In Yii 1 it seemed like this:

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

In Yii 2, the $ application is a property of Yii, not a method, so naturally this does not work, but changes it to:

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

causes this error:

 Getting unknown property: yii\web\Application::clientScript 

I could not find the documentation for Yii 2 on loading basic scripts, so I tried the following:

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

While this loads jQuery into the head, the second version of jQuery also loads Yii if necessary and therefore causes conflicts.

Also, I donโ€™t want to use the Yii jQuery implementation, I would prefer to keep my own and, therefore, thatโ€™s why I do it.

How can I load jQuery and other kernel files without Yii, loading duplicates of them when they need them?

+6
source share
2 answers

To disable the default Yii2 assets, you can refer to this question:

Yii2 disable Bootstrap Js, jQuery and CSS

In any case, the Yii2 asset management method differs from Yii 1.xx First you need to create an AssetBundle . As an official example of leadership, create an asset package as shown below in ``:

 namespace app\assets\YourAssetBundleName; use yii\web\AssetBundle; 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 post them in your views:

 use app\assets\YourAssetBundleName; YourAssetBundleName::register($this); 

Which $this refers to the current view object.


On the other hand, if you only need to register the JS files in the view, you can use:

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

yii \ web \ View :: registerJsFile ()

And if you need to register only CSS files in the view, you can use:

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

yii \ web \ View :: registerCssFile ()

+9
source

You can remove the main jQuery from the download as follows:

config /web.php

 'assetManager' => [ 'bundles' => [ // you can override AssetBundle configs here 'yii\web\JqueryAsset' => [ 'sourcePath' => null, 'js' => [] ], ], ], 
+2
source

Source: https://habr.com/ru/post/978541/


All Articles