1

Here is the script:

$("#button").click(function(){
    $.getScript('script.js', function(){
       script.init();
    });
});

I want to be able to run script.init() like the above example, but if I do it like this, I have to click the button twice to be able to get the script. -When it runs script.init() the first time, it is not loaded yet it seems.

So how can I make sure the script is loaded before I do something with it?

2 Answers 2

3

Try this:

$(window).load(function() {
    $.getScript('script.js', function() {
        $("#button").click(function() {
           script.init();
        });
    });
});

Or, try using the jQuery.ajax function instead of the shorthand:

$("#button").click(function () {
    $.ajax({
        url: "script.js",
        dataType: "script",
        success: function () { script.init(); }
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Yes I'm sure that will work, but I don't want to load the script until it is needed.
The second solution does the same thing... Button needs to be pressed twice. If I put it in a setTimeout it will work, but that is not the solution I want.
Solved. The script.js had a $(function(){ script.init()}; at bottom of the page, this seemed to interfere with the script. Removed, and now works!
Good job on the answer with ajax... There's success but also error, for function callback.
0

I have used this code to call the function when the function name is a string.

$.ajax({
    url: 'script.js',
    dataType: "script",
    success: function () { window["script"]["init"](); }
});

You could also pass the button into the function that you are calling.

$.ajax({
    url: 'scrpt.js',
    dataType: "script",
    context : this,
    success: function () { window["script"]["init"](this); }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.