2016-03-21 102 views
0

Javascript使用Yii2并创建一个资产包与我的CSS和JavaScript文件。我整合了一个现有的模板,并且一些JavaScripts在HEAD和其他在BODY的末尾被调用。我知道如果你想让他们在头上或身体的尽头,就有公共$ jsOptions来声明。但是有一种方法可以将头部和身体包含在内? 这是我的名单,我需要头4和头2。在<head>和末尾<body>

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的建议,删除引导和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], 
+0

它'在页面结尾处加载JavaScript文件是一种很好的做法。检查这[回答](http://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup)了。 –

+0

如果顺序是正确的,如果你在最后加载所有这些命令,应该没有什么区别,除非你的html中有'

1

您可以使用两种资产这样 在你AppAsset声明两个dependes

<?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,], 

} 

?>