I have one view in which I need to call JQuery in my header along with another JS Library. For all other pages they can be rendered at the end of the document. What's the best way to achieve this in Yii2?
Currently I am just doing this in my AppAsset.php
public $js = [
'https://code.highcharts.com/highcharts.js',
];
public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
I have looked at making a new Asset, but it didn't seem to work and I wasn't sure if it was the right way to go about it. As I don't want to render the JS first in every page.
<?php
namespace app\assets;
use yii\web\AssetBundle;
class EarlyJavaScriptAsset extends AssetBundle
{
public $js = [
'https://code.highcharts.com/highcharts.js',
];
public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
public $publishOptions = [
'only' => [
'report/report-1', // this is view folder location
]
];
}
If you would look at AssetBundle::register() you would see that it uses View::registerAssetBundle() without second parameter. But that second parameter is the thing you need:
@param integer|null $position if set, this forces a minimum position for javascript files. This will adjust depending assets javascript file position or fail if requirement can not be met. If this is null, asset bundles position settings will not be changed. See registerJsFile for more details on javascript position.
In your view, where you register your asset bundle, change
EarlyJavaScriptAsset::register($this);
to
$this->registerAssetBundle(EarlyJavaScriptAsset::className(), $this::POS_HEAD);
and
$this->registerAssetBundle(EarlyJavaScriptAsset::className(), $this::POS_END);
in second view
PS: Of course $this
is context of your View
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With