javascript加载外部文件并继续处理
因此,我试图避免加载某些脚本,直到用户需要它们,但我一直以使用 if...else 并在两个地方调用 continue 代码的模式结束。在下面的代码中,您可以看到对 continueProcessing() 方法的两次调用。有更好的方法吗?
if (typeof sessionList === "undefined" || typeof sessionList != "function") {
$.getScript('resources/sessionList.js', function() {
continueProcessing();
});
} else {
continueProcessing();
}
function continueProcessing() {
// do stuff
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我没有使用过 getScript,但在加载 html 模板时也遇到过类似的挑战。我一直在使用延迟/承诺方法。对于您的情况,它看起来像这样:
在脚本已经存在的情况下,jqXHR var不会被延迟,因此“then”会立即执行。
这仍然需要输入一些代码,但至少“ContinueProcessing”只出现一次。
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:
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.
对我来说这似乎是一个很好的方法。
This looks like a good way of doing it to me.
所以我使用了 $.Deferred 模式/代码并想出了这个。它不是那么简洁,但我认为这是一种更干净的方法。看起来我有很多代码需要重构......
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...