Eduardo Eduardo - 5 months ago 57
jQuery Question

Yii 2 and jQuery

Due project requirements I have to use a different version of jQuery than the one which comes with Yii2. I know I can disable it by using:

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


Then I go to AppAsset:

class AppAsset extends AssetBundle
{
public $sourcePath = "@app/themes/v1/assets";

public $jsOptions = [ 'position' => \yii\web\View::POS_END ];

public $js = [
"js/lib/jquery/jquery-1.9.1.js",

];
}


But this brings one big issue, jquery loads after yii.validation, etc:

</script><script src="/assets/5b466ff1/yii.js?v=1465857632"></script>
<script src="/assets/5b466ff1/yii.validation.js?v=1465857632"></script>
<script src="/assets/5b466ff1/yii.activeForm.js?v=1465857632"></script>
<script src="/assets/98d185b3/js/lib/jquery/jquery-1.9.1.js?v=1466702133"></script>


My temporal solution is changing POS_END to POS_HEAD, but that affects page SEO right?, as far as I know is considered bad practice to load js on head.

So my question is:

How can I load jQuery from my theme assets, using POS_END and loading before yii.validation etc?

A possibility is to add it on web/js/jquery.js but I would prefer to keep it on the assets bundle.

Any ideas?

Answer

Just Change Your Config Code as :

'assetManager' => [
        'bundles' => [
            'yii\web\JqueryAsset' => [
                'js' => ['lib/jquery/jquery-1.9.1.js'],
                'sourcePath' => '@app/themes/v1/assets/js'
            ]
        ]
    ]

No Need to Define jquery in AppAsset

class AppAsset extends AssetBundle
{
  public $sourcePath = "@app/themes/v1/assets";
  public $jsOptions = [ 'position' => \yii\web\View::POS_END ];
  public $js = [
    //"js/lib/jquery/jquery-1.9.1.js" Not Required
  ]; 
}