2009-11-13 61 views
3

<script>標籤內使用goog.require加載腳本時,不加載指定的文件。例如:在腳本塊中通過goog.require加載文件失敗

<script> 
goog.require('goog.dom'); 
var mydiv = goog.dom.$('foo'); 
</script> 

給出:

goog.dom is undefined 

什麼不對的使用情況如何?

回答

9

問題是goog.require動態地將所需的腳本標記添加到文檔之後的當前腳本標記。因此,舉例來說:

<script> 
goog.require('stuff'); 

doSomething(); 
</script> 

翻譯爲:

<script> 
goog.require('stuff'); 

doSomething(); 
</script> 
<script src=[included stuff] type="text/javascript"></script> 

解決的辦法是對要求獨立的腳本標籤:

<script> 
goog.require('stuff'); 
</script> 

<script> 
doSomething(); 
</script>