我使用 Yii2 并使用我的 css 和 javascript 文件创建了一个 Assets 包。我集成了一个现有模板,一些 javascript 在 HEAD 上调用,在 BODY 末尾调用其他 javascript。我知道有 public $jsOptions 来声明你是想要它们在头上还是在 body 的末端。但是有办法把一些放在头上,一些放在 body 上吗? 这是我的 list ,我需要头上的前 4 个和 body 上的后 2 个。
public $js = [
'js/jquery.min.js',
'js/bootstrap.min.js',
'js/custom.js',
'js/moment/moment.min.js',
'js/datepicker/daterangepicker.js',
'js/custom2.js'
];
我根据@chapskev 的建议删除了 bootstrap 和 jquery,然后我去了这里,并尝试实现第三个选项:http://www.yiiframework.com/doc-2.0/yii-web-assetbundle.html# $js-细节
public $js = [
'js/custom.js',
['js/moment/moment.min.js' => ['position' => View::POS_END]],
['js/datepicker/daterangepicker.js' => ['position' => View::POS_END]],
['js/custom2.js' => ['position' => View::POS_END]],
];
public $jsOptions = ['position' => View::POS_HEAD];
但我收到此错误:strncmp() 期望参数 1 为字符串,给定的数组,所以显然我做得不好所以我尝试了这个,没有给出错误,但不包括文件全部:
'js/custom2.js' => ['position' => \yii\web\View::POS_END],
最佳答案
您可以通过这种方式使用两个 Assets 在您的 AppAsset 中,您声明两个依赖项
<?php
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
'js/jquery.min.js',
'js/bootstrap.min.js',
'js/custom.js',
'js/moment/moment.min.js',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
'frontend\assets\HeaderAsset',
'frontend\assets\BodyAsset',
];
}
?>
然后创建 HeaderAsset.php
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
use yii\web\View;
class HeaderAsset extends AssetBundle
{
// The files are not web directory accessible, therefore we need
// to specify the sourcePath property. Notice the @vendor alias used.
public $basePath = '@webroot';
public $baseUrl = '@web';
public $js = [
'js/jquery.min.js',
'js/bootstrap.min.js',
'js/custom.js',
'js/moment/moment.min.js',
];
public $jsOptions = ['position'=> View::POS_HEAD,],
}
?>
和 BodyAsset.php
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
use yii\web\View;
class BodyAsset extends AssetBundle
{
// The files are not web directory accessible, therefore we need
// to specify the sourcePath property. Notice the @vendor alias used.
public $basePath = '@webroot';
public $baseUrl = '@web';
public $js = [
'js/datepicker/daterangepicker.js',
'js/custom2.js'
];
public $jsOptions = ['position' => View::POS_END,],
}
?>
关于<head> 和 <body> 末尾的 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36138218/