Why Keep JavaScript Code in Separate Files?

code-reusejavascriptpatterns-and-practicesprogramming practicesweb-development

In web development we are commonly used to keep Javascript code in separate files, but sometimes we need this Javascript code to manipulate server side data locally.

For example, making an Ajax Call to a dynamically created URL server side.

But some programmers My colleagues keep saying that plain Javascript in the JSP file is a sign of bad code, and wrong practices.

To what extent are they right ? Assuming that those blocks of code are not reusable in other pages, why is this practice perceived as a bad thing?

Edit :

Thanks for the quick answers, I'm still wondering how can I manage Dynamically created Javascript code (which cannot be cached, obviously). For example making an ajax call with an URL like this :

url : ${some_url_coming_from_server},

In my case the code is huge, and I have server-data everywhere, am I doing it wrong ?

Best Answer

First thing : A pure JS code in a separate file will be cached, reducing the amount of data transfered on each request.

Unless you have a very small, page specific JS code, you shouldn't inline it.

Other valid reasons are already pointed in Mike's answer.

If you have to pass some values from the server to the JS, what you can do instead of injecting JSP code directly in your JS is to create a function in your external file, and call it from your page, passing your dynamic values as parameters :

JSP:

<script>
    yourFunction(${param1}, ${param2}...);
</script>

JS external file:

function yourFunction (param1, param2...) {
    // do your stuff
}

Or even better, especially if you have a large amount of variables, create an object to pass as a parameter instead of passing a bunch of params :

JSP:

<script>
    var obj = {
        param1: ${param1},
        param2: ${param2}
        ...
    }
    yourFunction(obj)
</script>

JS external file:

function yourFunction (obj) {
    // do your stuff using obj.param1, obj.param2...
}