Loading core scripts such as jQuery in Yii 2

18,183

Solution 1

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 from Yii 1.x.x. First you need to create an AssetBundle. As official guide example, create an asset bundle like 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, to publish them on your views:

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

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:

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

yii\web\View::registerJsFile()

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

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

yii\web\View::registerCssFile()

Solution 2

You can remove the core jQuery from loading like so:

config/web.php

'assetManager' => [
    'bundles' => [
        // you can override AssetBundle configs here       
         'yii\web\JqueryAsset' => [
            'sourcePath' => null,
            'js' => [] 
        ],        
    ],
],
Share:
18,183
Brett
Author by

Brett

Updated on August 15, 2022

Comments

  • Brett
    Brett over 1 year

    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?

  • Brett
    Brett over 9 years
    Is that the only way to do it? No way similar to Yii 1?