Yii loading jquery multiple times

2019-08-08 23:24发布

问题:

I currently have a page which renders 6 partial views. The problem that I am now facing is that, because I need to set processOutput to TRUE, jquery is loaded multiple times.

I tried to resolve this by adding

    <?php Yii::app()->clientscript->scriptMap['jquery.min.js'] = FALSE; ?>
    <?php Yii::app()->clientscript->scriptMap['jquery.js'] = FALSE; ?>

To my partial view. The problem is, that by doing so, jquery doesn't load AT all.

Anyway to resolve this so it will only load once?

回答1:

Change your code to:

<?php $jquery = '/js/jquery.min.js'; ?>
<?php Yii::app()->clientscript->scriptMap['jquery.min.js'] = $jquery; ?>
<?php Yii::app()->clientscript->scriptMap['jquery.js'] = $jquery; ?>

With this approach, you can use the asset manager. Example:

<?php $jquery = Yii::app()->assetManager->publish(Yii::app()->theme->basePath . '/assets/jquery-1.9.1.js'); ?>
<?php Yii::app()->clientscript->scriptMap['jquery.min.js'] = $jquery; ?>
<?php Yii::app()->clientscript->scriptMap['jquery.js'] = $jquery; ?>


回答2:

You can include following ClientScript mapping in your config file under components array

'clientScript' => array(
        'scriptMap' => array(
            'jquery.js' => '/js/jquery.min.js', // set your path here
        ),
    ),

Also add following to your <head> section

Yii::app()->clientScript->registerCoreScript('jquery');

And remove anyother manual jquery include in your views. You should be fine.