Define Order On Registered Js

Is it possible to define the order of registered javascript (by $view->registerJs(); ) somehow?

I got the following situation:

My own View class:

class View extends \yii\web\View {

    public function init()



        $this->registerJs("Script A;");



In another view file i got this:

$this->registerJs("Script B;");

The problem (or actually it’s pretty logic) is that Script A is displayed before Script B:


    Script A;

    Script B;


But i want Script B to appear before Script A, is that possible?

You can do this with js files by using asset bundles and dependencies. This is not possible with inline javascript.

I’m afraid not.


Since the signature is public function registerJs($js, $position = self::POS_READY, $key = null) and the registering code is $this->js[$position][$key] = $js; you can try the following hack:

$this->registerJs("Script A;", self::POS_READY, 0);

$this->registerJs("Script B;", self::POS_READY, 1);

I wonder if it works :)

Thanks, Script A is not really dependent of Script B though and Script B is too dependant on the view (where it’s registered in) to put it in a seperate js file.

To make it more clear:

Script A does something with my layout, but it has to do it at the very last moment (after other javascript is executed).

Script B renders a carousel with specific options for each view where it’s registered in, but it changes my layout a bit as well.

If i can register a javascript file after the inline javascript it should be fixed as well, can i do that?

Or else, it’s maybe an idea to implement this feature so you can order inline javascript?

Nice idea, but it doesn’t work unfortunately.

Can you relook at your view layout design to achieve this? You can use multiple layouts and lay them out in your master view layout and render them the way you want.

I will, for now i placed the line of Script A in my layout manually, under $this->endBody();, that works.