2014-09-03 32 views
1

我正在使用Typesafe Activator 1.2.10並嘗試使用WebJars Sample for Play 2.x。我查看應用程序模板並閱讀Bootstrap依賴於jQuery。所以,當你指定Bootstrap作爲依賴時,你也會得到jQuery。在測試頁面。在Play Framework中使用jQuery WebJars示例應用程序

OK,我想我現在有jQuery的可用 - 讓我們嘗試一下,加入以下最低代碼index.scala.html(內<div class="container">):

<script type="text/javascript"> 
    $('.container').hide(); 
</script> 

不,Safari瀏覽器抱怨ReferenceError: Can't find variable: $。如果我在Safari的命令行中嘗試使用相同的代碼,它將起作用 - 所以jQuery不會立即加載,而是會在一段時間後立即加載。

我看了一些關於RequireJS使用和嘗試以下操作:

<script type="text/javascript"> 
    require(["jquery"], function() { 
    $('.container').hide(); 
    }); 
</script> 

現在我從Safari瀏覽器得到了以下錯誤:

[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (jquery.js, line 0) 
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (jquery.js, line 0) 
[Error] Error: Script error for: jquery 
http://requirejs.org/docs/errors.html#scripterror 

最後我在app/assets打開index.coffee腳本,並嘗試在這裏:

require ["bootstrap"],() -> 
    console.log "boostrap javascript loaded" 
    $('.container').hide() 

勝利終於!但是,將所有jQuery代碼寫入外部文件是非常令人討厭的。我怎樣才能讓jQuery在HTML模板中工作?我如何封裝代碼,以便只有在jQuery被RequireJS加載後才能執行代碼?謝謝!

回答

4

使用WebJars進行依賴管理會將傳遞依賴關係拉入項目中,但這並不意味着它們會奇蹟般地加載到頁面中。所以如果你想使用jQuery,那麼你需要加載它。您可以使用WebJars中的RequireJS支持加載傳遞依賴關係(如您發現的那樣)。如果你只是想將jQuery加載到index.scala.html一頁,然後做到這一點:

<script type='text/javascript' src='@routes.WebJarAssets.at(WebJarAssets.locate("jquery.min.js"))'></script> 

更多細節在WebJars文檔:http://www.webjars.org/documentation

相關問題