1

Please see example below. How do I call my function from within the loaded file?

Here is my external file, loaded with ajax:

// some-file-name.js
var api = {
    method1: function() {
        // doStuff here
    }
}

Here I am loading the file and hopefully invoking some function from the new methods provided:

// load script and do stuff with it when done
$.when(
   $.getScript("some-file-name.js"), 
   $.Deferred(function(deferred) {
       $(deferred.resolve);
})).done(function() {
    // how to call api.method1() when api.method1() gives me undefined? 

});

Any suggestions much appreciated.

5

1 Answer 1

0
// 1. $.getScript returns a Promise, no need for custom deferred
// 2. access your response. The Promise passes the response to the 
//    success handler parameter

$.when(
   $.get("some-file-name.js"), // 1
).done(
    function(api) {  // 2
      console.log(api.method1);
    }
});
Sign up to request clarification or add additional context in comments.

6 Comments

-1: a) the custom deferred was used to wait for DOM ready, nothing else b) as stated, the callback does not work. The script might not yet have been executed.
Oh, I have a very good idea. I even can read the docs: "The callback is fired once the script has been loaded but not necessarily executed" If you know more, please tell us.
a) wrap the statement in a $(document).ready({ }); b) $.getScript will return the script and execute it immediately, maybe with your requirement you should use $.get instead
a) Which statement, the console.log? Yes, that could work as well, but there's nothing wrong with the OP's use of deferred. Btw, if you know that $.ajax returns a promise, $.when is superfluous. b) How would $.get help here? Wouldn't it not execute the script, so that api.method fails for sure?
Please notice it's not my question :-) And No, in that snippet the ajax request would only start after DOM ready, which is not the intended behaviour. You could however do $.get("…").done(function(resp) { $(function() { // do whatever we want api.method1(); }); })
|

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.