Reputation: 634
So I'm trying to avoid loading certain scripts until the user needs them but I keep ending up in the pattern of using an if...else and putting the call to the continue code in both places. In the code below you can see the two calls to the continueProcessing() method. Is there a better way of doing this?
if (typeof sessionList === "undefined" || typeof sessionList != "function") {
$.getScript('resources/sessionList.js', function() {
continueProcessing();
});
} else {
continueProcessing();
}
function continueProcessing() {
// do stuff
}
Upvotes: 1
Views: 209
Reputation: 634
So I played with the $.Deferred pattern/code and I came up with this. It's not as terse but I think it's a cleaner way of doing it. Looks like I have a lot of code to refactor...
var dfd = $.Deferred();
if ( typeof sessionList === "undefined" || typeof sessionList != "function" ) {
$.getScript('resources/sessionList.js', function(){
dfd.resolve();
});
}
dfd.done(function() {
continueProcessing();
});
Upvotes: 0
Reputation: 11
I haven't used getScript, but have faced a similar challenge with loading html templates. I've been using the deferred / promise approach. It would look like this for your case:
var jqXHR = {};
if (typeof sessionList === "undefined" || typeof sessionList != "function") {
jqXHR = $.getScript('resources/sessionList.js');
}
$.when(jqXHR).then(continueProcessing());
In the case where the script already exists, the jqXHR var will not be a deferred, so the "then" is executed immediately.
This is still a bit of code to type, but at least "continueProcessing" only appears once.
Upvotes: 1