好吧,我对Yii2资产捆绑包不熟悉。Yii2资产捆绑包在页面顶部注册css文件,在页面底部注册js文件。但是,如何在页面顶部也包含这些js文件?
class AppAsset extends \yii\web\AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
Run Code Online (Sandbox Code Playgroud)
我只需要在页面顶部注册所有js和css文件即可。使用AppAsset,可以吗?
编辑
默认注册脚本
<head>
....
<link href="/assets/4850c11c/css/bootstrap.css" rel="stylesheet">
....
</head>
<body>
.....
<script src="/assets/76016e7c/jquery.js"></script>
.....
</body>
Run Code Online (Sandbox Code Playgroud)
我只需要
<head>
....
<link href="/assets/4850c11c/css/bootstrap.css" rel="stylesheet">
<script src="/assets/76016e7c/jquery.js"></script>
....
</head>
Run Code Online (Sandbox Code Playgroud)
小智 6
只需向您的捆绑类添加一行即可。
public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
Run Code Online (Sandbox Code Playgroud)
您的代码如下所示:
class AppAsset extends \yii\web\AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
public $js = [
'somefile.js'
];
}
Run Code Online (Sandbox Code Playgroud)
要将JavaScript文件包含在页面的顶部(默认情况下,正文部分的末尾包含JavaScript文件),请使用以下选项:
public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
Run Code Online (Sandbox Code Playgroud)
或直接在视野中
$this->registerJs('js/myjsfile.js', $this::POS_HEAD);
Run Code Online (Sandbox Code Playgroud)
您可以看到http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html
http://www.yiiframework.com/doc-2.0/guide-structure-assets.html