Search code examples
jqueryplayframeworkrequirejswebjars

Using jQuery in Play Framework WebJars sample app


I am using Typesafe Activator 1.2.10 and trying out the WebJars Sample for Play 2.x. I check out the application template and read Bootstrap depends on jQuery. So when you specify Bootstrap as a dependency you get jQuery too. in the test page.

OK, I guess I now have jQuery available - let's try it out by adding the following minimal code to index.scala.html (inside <div class="container">):

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

Nope, Safari complaints that ReferenceError: Can't find variable: $. If I try the same code in the Safari's command line, it works - so jQuery is not loaded immediately but after a while it's there.

I read something about RequireJS usage and try the following:

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

Now I get the following errors from 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

Finally I open the index.coffee script in app/assets and try here:

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

Victory at last! But it's really obnoxious to write all my jQuery code in an external file. How can I make jQuery work in the HTML templates? How do I encapsulate the code so that it's executed only after jQuery has been RequireJS-loaded? Thanks!


Solution

  • Dependency management with WebJars will pull the transitive dependencies into the project but that doesn't mean they magically get loaded in a page. So if you want to use jQuery then you need to load it. You can use the RequireJS support in WebJars to load transitive dependencies (as you discovered). If you just want to load jQuery into your index.scala.html page then do this:

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

    More details in the WebJars docs: http://www.webjars.org/documentation