You either need to make a synchronous call to the server, explicitly make the call in the response handler, or use a closure callback - either manually or using a continuation transformer such as Narrative JavaScript or djax. Note that you can't just add a loop to keep checking for the new function, due to the single-threaded nature of JavaScript. A less obtrusive way to do the same thing involves DOM Manipulation. Simply insert a suitable script element into the DOM and the JavaScript will be loaded.
220-602 It can be a child of either the head or body and its src property must be pointing to a JavaScript URL. There are several differences with XMLHttpRequest:
* The JavaScript will automatically be evaluated in much the same way as JavaScript linked in the static HTML is evaluated when the <script> tag is first encountered. You can declare a bare function or variable without adding it to the window.
* You can load JavaScript from external domains.
* The URL points to a specific Javascript resource. With XMLHttpRequest, there's more flexibility: you can, for example, send several JavaScript snippets inside different XML nodes.
* The DOM is affected in a different way. Even if the behaviour is transient, the script will be added to the DOM, whereas it would disappear after an XMLHttpRequest callback eval'd it.
(Watch for compatibility. See
640-553 * Inserting script element into the DOM means that if the file is cached in the browser then the cache is used. This is not possible with XMLHttpRequest. There's a variant of the pattern I'll call JavaScript Response in reference to the HTML Response pattern. The standard pattern refers to the situation where you're downloading a new set of functions, classes, and variables. In reality,
642-524 you're just adding new members to the DOM - some other code will then invoke it. In JavaScript Response, you grab a snippet of Javascript and eval it - the script is not wrapped inside a function (although it may define some functions that it calls). Under this variant, then, the browser is asking the server what to do next. Whereas in the standard pattern, the browser knows what to do, but not how to do it.