Search code examples
phpjqueryyii2assetbundle

Yii2 Register Asset Files (js) at the end of all js files


I am trying to add a js-file to my view via AssetBundles at the very end of the page.

When using the static approach with MyAssetBundle::register($this->view), I could use jsOptions with 'position' => \yii\web\View::POS_END, which works as it should.

However, I need to set some variables dynamically. Therefore I tried to work with an instance of the MyAssetBundle class and registerAssetFiles instead of register.

My approach:

$myAsset= new MyAssetBundle();
//...do some stuff with the variables (+ load different css/js files based on the variables)
$myAsset->registerAssetFiles($this->view);

Basically it still works, the problem is that the js-files are on top of all js-files, so f.e. if I use jQuery in my js-file, I get Uncaught ReferenceError: jQuery is not defined because the jQuery File is included after my file.

I'm pretty new to Yii - is there a way that I can include my files at the end of the js part?


Solution

  • After a whole day of research and checking dependencies, I came to a quite simple solution to the problem. Both of the answers above are correct - so I voted them up, but they did not fully fit my specific needs.

    The AssetBundle class comes up with a variable $depends and a variable $jsOptions - which did not work at it's own. But while checking dependencies I realized that the $jsOptions have a param depends as well.

    So I created a constructor, that sets the depends in $jsOptions to all my needed Assets, which have to be included before my files.

    My solution:

    class AjaxPanelAsset extends AssetBundle
    {
       public $basePath    = '@webroot';
       public $baseUrl     = '@web';
       public $css = [
    
       ];
       public $js = [
    
       ];
    
       public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
        'yii\bootstrap\BootstrapPluginAsset',
       ];
    
       public function setCSSJSFiles($css,$js)
       {
        $this->css = array($css);        
        $this->js = array($js);
       }
    
       public function __construct(){
        $this->jsOptions= ['depends' => $this->depends];
       }
    
    }