ESP Web Server calling javascript function
If you want server-push, you can use Server Sent Events or a Websocket instead of polling with XMLHttpRequest.

So yes, it can be done, and I have implemented both using a Nano 33 IoT at one end and Javascript in a browser on the other. Some example code is here: https://github.com/ocrdu/arduino-webinterface-sse and here: https://github.com/ocrdu/arduino-webinterface-websocket.

I don't know if there are convenient libraries for the ESPs to do this, though.