Reputation: 2680
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?
Upvotes: 1
Views: 8672
Reputation: 181
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); }
});
Upvotes: 0
Reputation: 486
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(); }
});
});
Upvotes: 3