dongtong1226 2016-01-19 15:56
浏览 33
已采纳

条件AppAssets

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
    ]
];
}
  • 写回答

1条回答 默认 最新

  • dongsan6889 2016-01-19 23:48
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作