How do I separate out constants for JavaScript?

302 Views Asked by At

I have a web-page created with JavaServer Pages (JSP) and with significant JavaScript (JS) that makes calls to other servers. The URL that the page talks to depends on what server (read: environment) I deploy to.

I have two possible strategies (at least) that I can use.

  1. I can define a server name constant in a JS file and use a script tag on that web page.
  2. I can write a JS variable with the JSP page, as some sort of dynamic content.

I'm leaning heavily on strategy 1, but am unsure if either of these is really better. I'd like to know what best practice is, and why.

1

There are 1 best solutions below

3
Andrew On

I have the same problem, to be honest I have no idea what the 'correct' way to do it is either, but I do hate global vars, so I currently do it this way,

In the jsp,

<script src="${pageContext.request.contextPath}/js/script.min.js"></script>
<script type="text/javascript">
     init('${pageContext.request.contextPath}');
</script>

Then the js is,

function init(baseURL, undefined){
  ...
}

No global vars to worry about then.