我想使用$.getScript为javascript文件创建一个模块加载器,但是由于脚本的加载是异步的,所以当我将模块的函数调用放入文档中时,它们可能会在模块加载之前被调用。有没有什么方法可以避免这种情况,比如让函数调用保持到模块成功加载?
framework.core.js:
var Framework = $.extend(Framework, Framework.Core = {
modules: [
'Module1',
'Module2'
],
init: function () {
$.each(modules, function (index, value) {
$.getScript('framework.' + value.toLowerCase() + '.js', function () {
});
});
}
});
Framework.Core.init();site.html:
<html>
<head>
<script src="framework.core.js"></script>
<script>Framework.Module1.functionCall();</script> // Call a function independent of the completion of the framework.core.js loader
</head>
... 发布于 2012-08-07 05:42:42
您将需要打开success回调,以使依赖函数与其挂钩。您将无法延迟执行以下函数以等待模块(除非您希望通过document.write插入脚本),因此回调是必要的。最好是将Deferred对象(由ajax函数返回)公开即可。此外,您根本不应该对该任务使用jQuery.getScript/,因为它会阻止缓存。
var Framework = $.extend(Framework, Framework.Core = {
// The "Core" property seems pretty useless, by the way ^^
modules: [
'Module1',
'Module2'
],
loads: {},
init: function () {
$.each(this.modules, function(index, value) {
this.loads[value] = $.ajax({
url: 'framework.' + value.toLowerCase() + '.js',
cache:true,
dataType:"script"
});
});
}
});
Framework.init();
<html>
<head>
<script src="framework.core.js"></script>
<script>Framework.loads.Module1.then(function() {
functionCall();
}); // Call a function as soon as the module is loaded
</script>
</head>
... https://stackoverflow.com/questions/11835914
复制相似问题