3

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.

  • Your question is not clear what do you mean for App.init ..have you error in your browser console .. What do you expect to do from the function – ScaisEdge Feb 07 '17 at 07:04
  • What you mean `does not work`? Do you have js files in correct order? Do you have single jQuery library loaded? Do you get any errors in console? – Justinas Feb 07 '17 at 07:13
  • It's not important what does this function. I'm sure, Javascript file is correct, because it's working in simple html file. It doesn't work in Yii Project. – satik-stack Feb 07 '17 at 07:15
  • all files are loaded correctly. – satik-stack Feb 07 '17 at 07:16
  • Can you please mention what error you are getting? how would we know what "why it does not work" mean? – Chinmay Waghmare Feb 07 '17 at 08:42
  • It does not work means it's doing nothing. Nothing happens. No errors, no any action. I edited question. Please, look it once again. – satik-stack Feb 07 '17 at 11:46

2 Answers2

4

$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);
Skatox
  • 4,237
  • 12
  • 42
  • 47
Kandarp Patel
  • 1,045
  • 9
  • 21
0

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.

Moldovan Andrei
  • 305
  • 1
  • 6
  • 19