duplication of CSS and JS files when using renderAjax()

Hi!

When i’m rendering view file by renderAjax() i have duplicated JS and CSS files, such as jQuery.js, bootstrap.css etc. How can i remove them?

If you are rendering a partial from a controller method, just use return rather than render, eg




public function actionTest

{

\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;


other code here


return $yourResults;// automatically json_encoded

}



I’m rendering widgets like depdrop and other, and i need their JS and CSS assets. I just want to know how i can remove manualy some of assets from controller or view.

Well, i went to dependencies of thoose widgets and commented them (there was bootstrap and like that which are already included), so now i’m not having duplicated assets but i don’t think it is the right way.

This is something you can’t really avoid.

renderAjax does not know (and can’t know) which js and css have already been included in the calling page.

You can try to do some script unregister before the output is sent to the client but I do no t think is worth the effort.

The browser already loaded and cached these script and it won’t load them again.

Well, thanks for advice.

You can create a hidden depdrop and add "use kartik\widgets\DepDrop;" to your controller, this will include all the files it needs, not pretty but it works!

If you know you do not need to load jQuery and/or JUI within the view file, just put at the end:

unset($this->assetBundles[‘yii\web\YiiAsset’]);

unset($this->assetBundles[‘yii\web\JqueryAsset’]);

so the renderAjax method loads just the assets that are left…

I personally handle this in a common controller (I also use this controller to manage RBAC so you don’t have to do it in a lot of places) i made that overrides the default render function. It works really well for my use and it sounds like it will for you as well. You would make your controllers extend your custom controller like the example below.





namespace common\controllers;


use Yii;


class Controller extends \yii\web\Controller {


    /**

 	*

 	* @inherdocs

 	*/

    public function render($view, $params = []) {

        if (Yii::$app->request->isAjax) {

            Yii::$app->assetManager->bundles = [

                'yii\bootstrap\BootstrapPluginAsset' => false,

                'yii\bootstrap\BootstrapAsset' => false,

                'yii\web\JqueryAsset' => false

            ];

            return $this->renderAjax($view, $params);

        }

        $content = $this->view->render($view, $params, $this);

        return $this->renderContent($content);

    }


}