0

I'm loading some javascript code via ajax (as a <script> block inside an html string), and I'm using jquery.html() to inject that payload into a <div>. The jquery.html() method automatically evals injected <script> elements.

I would like to wait for the code in the <script> block to complete execution before releasing execution back to the main event loop. Even if the <script> contains callbacks, like an $.ajax().done() or setInterval(). Even if it causes an infinite loop, and even if it blocks any other events from being processed for a very long time.

Is this possible? I'm just wondering if there's some kind of synchronization-wrapper browser-supported utility in Javascript. My hunch is no, since this seems contrary to the single event-loop nature of Javascript, but I thought I'd check :) Ultimately, my goal is to insert custom javascript into the page upon a specific user action, and guarantee that the code will be executed in its entirety.

Note that I don't need to use jquery.html() or <script> injection, that's just my starting point. Maybe the best I can do is tell the client to invoke a specific pre-defined callback function when their code is finished, and make sure I don't change the window until this function is invoked?

2
  • 1
    No, there's no generic way to wait for all callbacks to finish. jQuery uses eval to execute the script block, so it will wait for all the synchronous actions to finish. Commented Apr 10, 2015 at 0:23
  • You cannot "wait" for anything to be done before "releasing" execution back to the main loop. That simply cannot be done in Javascript. Commented Apr 10, 2015 at 0:25

1 Answer 1

1

You cannot "wait for the code in the block to complete execution before releasing execution back to the main event loop" in Javascript. That simply cannot be done.

Done right, you could insert the script tags with onload handlers so you would be notified (via a callback) when those scripts had finished loading and finished their synchronous execution (but not their async execution).

If you wanted to know when async execution in those scripts would be done, you would have to build something into those scripts to notify you when they were done.

If you're going to use jQuery's .html() to do script tag injection you lose a lot of control over this process and it becomes a hacking project to try to figure out what you can do from outside the process.

In all cases, you cannot prevent the continuing execution of the main event loop of javascript while waiting for this all to finish.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.