Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play! Framework: Best practice to use URLs in separate JavaScript files?

I am currently reorganizing a Play! project where there is a lot of JS code in the HTML template files. This code should be moved to external JS files for better readability and faster page loading times. However, when I just create a JS file in the public folder, all the @{Controller.method} link replacements are no longer working. I was thinking about calling some initialization function from the HTML templates which just supplies the required URLs like

initialize({ "Application.doThis" : "@{Application.doThis}"})

however this is becoming very cumbersome and error-prone with any URL that is added. Another thing is, that the I18N also no longer works. So what is the best practice for scenarios like these, where you have your JS code in a separate file but still want to use URL generation and I18N in your JS?

like image 710
Jan Thomä Avatar asked Nov 17 '10 21:11

Jan Thomä


People also ask

Should I separate JavaScript files?

You should put your JS code in a separate file because this makes it easier to test and develop. The question of how you serve the code is a different matter. Serving the HTML and the JS separately has the advantage that a client can cache the JS.

Should all my JavaScript be in one file?

To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.

Can you link two JavaScript files together?

We can include a JavaScript file in another JavaScript file using the native ES6 module system. This allows us to share code between different JavaScript files and achieve modularity in the code. There are other ways to include a JS file like Node JS require, jQuery's getScript function, and Fetch Loading.

What are the benefits to segregate HTML and JavaScript files?

Separation of concerns - HTML/CSS/JavaScript should be separate. It makes working with them easier. You know exactly where to locate certain areas, plus other developers can work on the likes of HTML, CSS and JavaScript independently.


1 Answers

In the main template, generate a 'Javascript router', something like:

<script>
    var routes = {
        doThis: #{jsAction @Application.doThis(user, ':param1', ':param2') /},
        doThat: #{jsAction @doThat() /}
    } 
</script>

And then in any 'static' javascript file, use this router:

$.get(routes.doThis({param1: x, param2: 'yop'}))
like image 138
Guillaume Bort Avatar answered Oct 21 '22 07:10

Guillaume Bort