Reputation: 597114
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.
Upvotes: 0
Views: 269
Reputation: 3301
Usually a better idea is to pass the config explicitly when initializing components defined in the external script, like this:
<script type="text/javascript" src="js/scripts.js"></script>
<script type="text/javascript">
MyApp.init(${config});
</script>
Upvotes: 1
Reputation: 28040
In general, I would say it is best practice to make javascript files self-contained, and not depend on any external variables.
That said, there are some circumstances where depending on external variables is the right thing to do, and I would say this is one of them. Note:
Upvotes: 1
Reputation: 169603
Assuming the specific values of your configuration variables are only known at runtime (ie the configuration can't be generated statically), it makes no sense to include the configuration in the actual script as that would make proper caching impossible.
It might be a good idea to dynamically generate a dedicated config.js
on the server-side instead of embedding the configuration into the HTML if the rest of the page is static (or only re-generated on content change). If the page is dynamic anyway, I see nothing wrong with embedding the configuration.
If you subscribe to the philosophy of completely separating markup and scripting, you could encode the configration in the markup (eg via the lang
attribute and cutom classes), but the purist viewpoint is not necessarily most pertinent.
Upvotes: 1
Reputation: 1038890
You could follow the example used in jquery plugins. They define default values for the parameters in a specific format which could be overloaded by the user. So in my opinion it is OK to allow the user the possibility to define some variables in a documented format which would be used by the external script.
Upvotes: 1