在Play Framework中使用jQuery WebJars示例应用程序
我正在使用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加载后才能执行代码?谢谢!
使用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