I think it depends on where you put the code. The error should be gone if it's triggered after mxui.js loaded. However, i don't think you can create something on server before you can login.
Hi Abhinay,
I am not sure what you are trying to achieve but adding javascript code to a mendix application should be done inside a custom widget. Inside the widget you can load the mx library using the define construct - you can find more details here https://docs.mendix.com/howto/custom-widget-development/create-a-basic-hello-world-custom-widget
Without a custom widget you have to find a way to load all mendix libraries and dependencies manually, but I would not recommend going down this route.
-Andrej
PS: Do you allow anonymous users in your App?