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
}
-
1Better way means less code & call the continueProcessing() once instead of twice ?David Tran– David Tran2011年10月25日 18:55:30 +00:00Commented Oct 25, 2011 at 18:55
-
I dunno. That just doesn't look right to me but the only other thing I can think of is using a timer in a loop and that seems worse. I definitely don't want to over-complicate this and that's about as simple as it gets.Jay– Jay2011年10月25日 19:07:05 +00:00Commented Oct 25, 2011 at 19:07
3 Answers 3
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.
2 Comments
$.when if you just have a single jqXHR as jqXHR objects already implement the promise interface. And initializing jqXHR as an object isn't necessary either - better use null.This looks like a good way of doing it to me.
Comments
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();
});