How to Run JavaScript Code Only After Document is Ready

I’m trying to run some JavaScript code in Frappe, but it’s not working as expected when I run it normally. It seems to be executing before the document is ready. However, the same code works fine when I run it after the document is ready.

How can I ensure that my JavaScript code runs only after the document is fully loaded in Frappe? Specifically, I want it to run only after a new document is created.

This is my current working code. I’m doing this with setTimeout for now, but I need the best way to do this.

For reference, please check this post