简体   繁体   中英

How do I separate out constants for JavaScript?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM