Is it a good practice for a .js file to rely on variables declared in the including html
Posted
by
Bozho
on Stack Overflow
See other posts from Stack Overflow
or by Bozho
Published on 2011-01-15T09:46:49Z
Indexed on
2011/01/15
9:54 UTC
Read the original article
Hit count: 179
JavaScript
In short:
<script type="text/javascript">
var root = '${config.root}';
var userLanguage = '${config.language}';
var userTimezone = '${config.timezone}';
</script>
<script type="text/javascript" src="js/scripts.js"></script>
And then, in scripts.js
, rely on these variables:
if (userLanguage == 'en') { .. }
The ${..}
is simply a placeholder for a value in the script that generates the page. It can be php, jsp, asp, whatever. The point is - it is dynamic, and hence it can't be part of the .js
file (which is static).
So, is it OK for the static javascript file to rely on these externally defined configuration variables? (they are mainly configuration, of course).
Or is it preferred to make the .js
file be served dynamically as well (i.e. make it a .php / .jsp, with the proper Content-Type
), and have these values defined in there.
© Stack Overflow or respective owner