0

I'm using the Play Framework and am trying to define a javascript file within a function in another javascript file (the reason being that I don't want these functions to be usable outside of the container function).

So I have two javascripts files, ./public/javascripts/main.js, ./public/javascript/custom.js.

From my html pages (index.scala.html) I define this as follows:

  <script src="@routes.Assets.at("javascripts/main.js")"></script>

Using "@routes...." doesn't work in main.js, so I tried adding the following:

  $.getScript("public/javascripts/custom.js", function(){
       alert("Script loaded and executed.");
    });

I've tried a variety of paths but it always says it can't find it.

Any idea how to do this in Play please? Looked through as much documentation as I can and nothing is there...

Any help would be brilliant!

Thank you.

Kind Regards,

Gary Shergill

Tair
  • 3,779
  • 2
  • 20
  • 33
Gary
  • 395
  • 2
  • 7
  • 24

2 Answers2

4

Make sure you have the following declaration in your routes file:

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.at(path="/public", file)

Then the following should work:

$.getScript("/assets/javascripts/custom.js", function(){
   alert("Script loaded and executed.");
});
josephpconley
  • 1,703
  • 12
  • 12
  • This returns the following: GET http://localhost:9000/assets/javascript/custom.js?_=1390575856602 404 Not Found – Gary Jan 24 '14 at 15:06
  • Which directory contains your js files? `javascript` or `javascripts`? The path returning 404 is looking in `javascript` (singular). Is that right? – mantithetical Jan 24 '14 at 15:30
  • Good spot... I seem to have missed out the "s" when typing it out. Thanks! – Gary Jan 24 '14 at 15:49
  • Question - In the future, is it more efficient to use "" or to use the above method ($.getScript....)? – Gary Jan 24 '14 at 16:10
1

Try to use Javascript Routing mechanism. As described here

Define javascriptRoutes

  import play.api.mvc._
  object Application extends Controller {

    def javascriptRoutes = Action { implicit request =>
      import routes.javascript._
      Ok(
        Routes.javascriptRouter("jsRoutes")(
           javascript.Assets.at     
        )
      ).as("text/javascript")
    }
  }

Update your .routes file

   GET  /routes   controllers.Application.javascriptRoutes

Include it into the page:

<script type="text/javascript" src="@routes.Application.javascriptRoutes"></script>

And then use jsRoutes variable in your javascript:

$.getScript(jsRoutes.controllers.Assets.at('javascripts/custom.js').url, function(){
    alert("Script loaded and executed.");
});
  • I don't fully understand the documentation regarding this. I need to add the def javascriptRoutes into the Application.java, but then what do I add to the routes file for this? Or is that wrong? – Gary Jan 24 '14 at 15:18