How to execute my js code after yii.js is fully executed?

I try to run my js code ‘$.ajax({…});’ just after page is loaded.
The problem is, that even if I run my code on 'loa’d event the “window.yii.initModule(window.yii);” from yii.js is not executed yet.

initModule function puts csrf token to XHR request, so my first(only first) XHR requests and with “Bad Request (#400): Unable to verify your data submission.” due to lack of csrf.

I’d like to avoid “setTimeout(function(){…”, howewer it works.
BTW i don have that problem on PC just, but on Galaxy S9 it appears always.

put your js in a file and include it in js of AppAsset it should load in order, AppAsset depends on YiiAsset so it should work as expected

@alirz23 I already did it and actually it coused, that my script goes aftes yii.js in source of the page, but that didn’ solve the problem. My script is small and I think that it is executec before yii.js managed to initialise it’s root js module. As bad workaround it is anough to wait 10ms in my script or put CSRF into AJAX manually. I’m not satisfied with them.

I don’t understand how is that possible, AppAsset has YiiAsset as a dependency and will load only after AppAsset script.

@alirz23 Here is the sequence:

<script src="/assets/7efd363c/yii.js"></script>
<script src="/assets/d146beb8/js/bootstrap-slider.min.js"></script>
<script src="/assets/c426a010/js/bootstrap-toggle.min.js"></script>
<script src="/js/scripts.js"></script>
<script src="/assets/44cefb6d/js/kv-widgets.min.js"></script>
<script src="/assets/ddae46b2/js/bootstrap.js"></script>

adding dependencies to asset caused that /js/scripts.js went after yii.js, but it is not enough.
To debug i placed alert() in:

  1. at the beginning of yii.js
  2. at the beginning of scripts.js
  3. in initCsrfHandler() in yii.js
  4. in jQuery(window).on(‘load’, function () in my script scripts.js

On Chrome I got the following order: 1,2,3,4 and everythin is fine. CSRF handler is initialised before window load.
On Edge, IE, Samsung Galaxy S9 the order is 1,2,4,3 !.
So CSRF handler is not initialised before my first ajax call in on load.