2012-08-06 70 views
1

我想使用$ .getScript爲javascript文件創建一個模塊加載器,但是因爲當我將一個模塊的函數調用放入他們可能會在模塊加載之前調用它們。有什麼辦法可以避免這種情況,也許可以通過保持函數調用直到模塊成功加載?動態加載js模塊並提供即時訪問裏面的功能

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> 
... 
+0

讓函數等待模塊和domready中,但不要讓準備好等待劇本。 – Bergi 2012-08-06 21:09:38

+0

問題是我想提供獨立於DOM就緒事件加載模塊的功能。如果我的文檔主體內部有一些腳本標籤調用模塊中的函數,那麼應該在模塊加載後立即執行它們。 – 2012-08-06 21:15:59

+1

是的,只需將它們掛接到模塊腳本的加載回調。 – Bergi 2012-08-06 21:18:40

回答

0

您將需要打開的成功回調將取決於功能勾就可以了。您將無法推遲執行那些以下函數來等待模塊(除非您通過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> 
...