I am not 100% sure that this is exactly your problem. One way to check would be to see if undefined errors appear in your browser console when you open the application.
If this is indeed the issue then IOP: The safest and most reliable way to fix it is to build your own Custom Widget wrapper. Custom widgets in mendix use AMD to explicitly define what needs to be loaded before the code is run.
If you don"t have any experiance with custom widgets and it seems like a lot of effort, then you need to find a way to enforce the order in which order your snippets get executed in the browser.
Luckily you will find plenty of information online about this.
You can use ths answer to start https://stackoverflow.com/questions/8100576/how-to-check-if-dom-is-ready-without-a-framework