Search code examples
yii2assetbundle

yii2 asset bundle - single file position


I am doing a web app on Yii2 framework. Defined (extended) new AssetBundle

class NeonAsset extends AssetBundle {
   public $sourcePath = '@app/themes/neon/';

   public $css = [
    'css/font-icons/entypo/css/entypo.css',
    '...',
    '...'        
   ];

   public $js = [
      'js/be_in_head_tag.js',
      '...',
      '...',
   ];
}

When rendered, CSS files are being published in <head> tag, and JS files at the bottom of <body> tag. It is ok.
But I want a single be_in_head_tag.js file to be published in <head> tag. And when I use $jsOptions it moves all JS files into the <head> tag.
Is it possible to make options only for one file?


Solution

  • One of the variants make that file into a separate asset class:

    class HeadPublishAsset extends AssetBundle {
        public $sourcePath = '@app/themes/neon/';
        public $js = ['js/be_in_head_tag.js'];
        public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
    }
    

    And add a dependency to your base class like:

    class NeonAsset extends AssetBundle {
        ...
        public $depends = ['app\assets\HeadPublishAsset'];
        ...
    }