Search code examples
jqueryyiiyii2

How can I registers jQuery assets inside head tag?


Well I am not familiar with Yii2 asset bundles. Yii2 asset bundle registers css files on the top of the page and js files on the bottom of the page. But How can I include those js files too on the top of the page?

class AppAsset extends \yii\web\AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

I just need all the js and css file to be registered on the top of the page. Using AppAsset, Is it posible?

EDIT

default registered scripts

<head>
....
<link href="/assets/4850c11c/css/bootstrap.css" rel="stylesheet">
....
</head>
<body>
.....
<script src="/assets/76016e7c/jquery.js"></script>
.....
</body>

I just need

<head>
....
<link href="/assets/4850c11c/css/bootstrap.css" rel="stylesheet">
<script src="/assets/76016e7c/jquery.js"></script>
....
</head>

Solution

  • Just add one line to your bundle class.

    public $jsOptions = ['position' => \yii\web\View::POS_HEAD];
    

    Your code will look like this then:

    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'
        ];
    }
    

    Alternatively, you can also specify just the files you want in header section using a config array instead of string (Warning: The first element must be the filename).

    class AppAsset extends \yii\web\AssetBundle
    {
        public $basePath = '@webroot';
        public $baseUrl = '@web';
    
        public $depends = [
            'yii\web\YiiAsset',
            'yii\bootstrap\BootstrapAsset',
        ];
    
        public $js = [
            'this_file_will_be_at_end.js', // The default position
            ['but_this_will_be_at_header.js', 'position' => \yii\web\View::POS_HEAD],
            ['and_this_too.js', 'position' => \yii\web\View::POS_HEAD]
        ];
    }