Yii2 package - single file position

I am making a Yii2 based web application. 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 rendering, CSS files are published in the <head> and JS files at the bottom of the <body> . This is normal.
But I want one be_in_head_tag.js file to be published in the <head> . And when I use $jsOptions , it moves all the JS files to the <head> .
Is it possible to create options for only one file?

+6
source share
2 answers

One option makes this 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 the dependency to the base class, for example:

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

I don’t know if there is an official way to do this (maybe not as if the specification of the options object was too complicated), however there is another simpler way compared to the accepted answer, which does not require you to create another AssetBundle .

All you have to do is create another array, for example:

 public $head_js = [ "path/to/src.js" ]; 

Then override the registerAssetFiles function as follows:

 public function registerAssetFiles($view) { foreach($this->head_js as $js) { $options = []; $options["position"] = \yii\web\View::POS_HEAD; $url = Url::to($this->baseUrl . "/" . $js); $view->registerJsFile($url, $options); } parent::registerAssetFiles($view); } 
0
source

Source: https://habr.com/ru/post/988314/


All Articles