Yii2 如何给脚本标签添加参数

Yii2 How to add parameters to script tag

获取渲染的 JS 资产如下所示:

<script src="/assets/a00ccd3f/jquery.min.js"></script>

我需要给它添加 async="async" 标签。

所以它应该看起来像

<script src="/assets/a00ccd3f/jquery.min.js" async="async" ></script>

我该怎么做?

在你自己的AssetBundle中你可以添加

public $jsOptions = [
    'async' => 'async',
];

如果您想将其添加到 Yii2 JqueryAsset 包(或其他包)中,您可以将其添加到配置的组件部分:

'assetManager' => [
    'bundles' => [
        'yii\web\JqueryAsset' => [
            'jsOptions' => [
                'async' => 'async'
            ],
        ],
    ],
],

像这样

<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace frontend\assets;
use yii\web\AssetBundle;
class ThemeCustomAsset extends AssetBundle
{
public $basePath    = '@webroot';
public $baseUrl     = '@web';
public $css = [];
public $js = [
    "js/lazysizes.min.js"
];
public $depends = [
    #'yii\web\YiiAsset',
    #'yii\bootstrap\BootstrapAsset',
];
public $jsOptions = ['async' => 'async'];
}