satik-stack
satik-stack

Reputation: 79

Yii2. $(document).ready troubleshooting

AppAsset:

    public $js = [
    'plugins/jquery/jquery.min.js',
    'plugins/jquery/jquery-migrate.min.js',
    'app.js',
];

So I'm wiriting in view file:

 $script = <<< JS
    jQuery(document).ready(function() {
        App.init();
      });
    JS;
 $this->registerJs($script, View::POS_END);

It's not working in Yii in view file, I mean nothing happens. In simple html it's like:

<script>
jQuery(document).ready(function() {
    App.init();
});
</script>

And it's working.

I can't understand why it does not work in Yii.

Upvotes: 3

Views: 2589

Answers (2)

Moldovan Andrei
Moldovan Andrei

Reputation: 315

Yii2, by default, loads the javascript after the jQuery. In the AppAsset.php, after the $js[] array, add the following code:

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

Now it should work properly.

Upvotes: 0

Kandarp Patel
Kandarp Patel

Reputation: 1020

$this->registerJs() creates a document ready wrapper by default, you just need to add the script which you want to include on a specific view in the first param of the function

$script='App.init();'; 
$this->registerJs($script);

Upvotes: 4

Related Questions