Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - How to include external js in view file in last position

Tags:

php

yii2

I have some query like how to include js file in last position after jquery file includes. beacuse whats the problem right now is my js load first and after that my jQuery file loads. like right now i have added file like:

use frontend\assets\AppAsset;

AppAsset::register($this);
$this->registerJsFile('@frontend_base/web/js/sendverification.js'); 

so this will add js file but not in last. so how i can achive this?

like image 603
Ishan Shah Avatar asked Jan 06 '16 13:01

Ishan Shah


3 Answers

The recommended solution is to use AssetBundles. Something like:

class SendverificationAsset extends AssetBundle {
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $js = [
        'js/sendverification.js'
    ];
    public $depends = [
        'yii\web\JqueryAsset'
    ];
}

Then in your view file:

use frontend\assets\AppAsset;
use frontend\assets\SendverificationAsset;

AppAsset::register($this);
SendverificationAsset::register($this);

The dependency will make sure that SendverificationAsset's Javascript and/or CSS always come after whatever JQuery includes.

Using AssetBundles also gives you the advantage of easily being able to minify/compress your code for production use.

like image 151
David Newcomb Avatar answered Nov 15 '22 15:11

David Newcomb


You can actually make your script have a dependency on jQuery. This is the only real way, without using inclusion pattern oddities, to ensure this:

$this->registerJsFile('@frontend_base/web/js/sendverification.js', ['depends' => 'yii\web\JqueryAsset'])

Using the POS_ constants only ensure that the JS is included at a certain part of the page, not after a certain file and can be included before that file.

You can read more here: http://www.yiiframework.com/doc-2.0/yii-web-view.html#registerJsFile()-detail

like image 23
Sammaye Avatar answered Nov 15 '22 17:11

Sammaye


You can define position of Js File as Register Js File

$this->registerJsFile('@frontend_base/web/js/sendverification.js',['position' => \yii\web\View::POS_END]); 
like image 39
Double H Avatar answered Nov 15 '22 16:11

Double H