Reputation: 183519
I'm developing a plugin that makes use of two other plugins. I was planning on using .getScript() to load the other two scripts, but I'm wondering how best to do this. Specifically, if the call is async, how can I guarantee that the scripts are loaded before the plugin is initialized? Would it be smarter to make the calls not async? (Is that possible? )
Code:
(function($){
// Is this the right place?
$.getScript('plugin1.js', function() {});
$.getScript('plugin2.js', function() {});
// Plugin stuff:
$.fn.myPlugin = function() {
return this.each(function() {
// Dependent plugins better be loaded by this point!
}); // End of this.each(...)
}; // End of plugin
})(jQuery); // End of closure
Thanks-
Upvotes: 1
Views: 1123
Reputation: 6260
The $.getScript();
method is basically a wrapper for the $.ajax();
method. This means it should be hooked into the jQuery Deferred object.
Try this:
var loading = $.getScript('myScript.js');
$.when( loading ).then(function() {
// Start your plugin code here.
});
Multiple Actions
var script_1 = $.getScript('myScript.js');
var script_2 = $.getScript('myScript2.js');
$.when( script_1, script_2 ).then(function() {
// Start your plugin code here.
});
Upvotes: 2
Reputation: 23662
I'm not sure if this is the most efficient way of doing this, but why not:
$.getScript('plugin1.js', function() {
$.getScript('plugin2.js', function() {
(function($){
// Plugin stuff:
$.fn.myPlugin = function() {
return this.each(function() {
// Dependent plugins better be loaded by this point!
}); // End of this.each(...)
}; // End of plugin
})(jQuery); // End of closure
});
});
Update: Regarding asynchronicity, you should consider whether you don't mind keeping your users waiting at least until both these files are fetched.
Upvotes: 0
Reputation: 966
getScript isn't really a great decision when you have scripts you know you're going to need -- just make sure you include both plugins as <script>
elements above your own.
But you could do:
(function($){
var plugin1Loaded = false;
var plugin2Loaded = false;
$.getScript('plugin1.js', function() {plugin1Loaded = true;});
$.getScript('plugin2.js', function() {plugin2Loaded = true;});
$.fn.myPlugin = function() {
if (plugin1Loaded && plugin2Loaded) {
...
}
}; // End of plugin
})(jQuery); // End of closure
Upvotes: 1