We have javascript files that are environment specific, and so I was thinking of going down the path of creating a generic way to read in an XML (config) file to store different environment specific settings. I was curious to know if anybody else on h开发者_高级运维ere does that (or if not, is there a reason why you don't)?
All you need to do is load a javascript file with some variable definitions, ideally namespaced. You can use a single object literal for this:
var config = {
option1: 'goods',
option2: {name: 'option2'},
option3: ['o','p','t','3']
}
Then load that file as your first script and you will have access to config information in each subsequent script eg
if (config.option1 == 'goods') doStuff();
JSON is hundreds of times faster to consume than XML, bring a native JavaScript object itself. Attach and forget.
EDIT:
James Westgate's example is JSON. You can use this inline or as an external file or even loaded via AJAX.
Here is another example:
var clientData = {}
clientData.dataset1 = [
{name:'Dave', age:'41', userid:2345},
{name:'Vera', age:'32', userid:9856}
]
alert(clientData.dataset1[0].name)
Why not use a separate js file to store your environment-specific settings?
Just like you can use multiple CSS files to style your page, you can use multiple js files as well.
So you could create a file called app-config.js with specific settings:
var SiteName = "MyWebsite.com";
var HeaderImage = "http://mycdn.com/images/mywebsite/header.png";
And then you include the js on your pages like this:
<script type="text/javascript" src="/js/app-config.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
One thing you might consider is to have the pages themselves include little Javascript blocks to provide just this sort of configuration information. Often, you really only need a small amount of information for URL building etc. I'll give a JSP example:
<script>
var appConfig = {
'syndicate': '${environ.syndicate}',
'urlBase': '${environ.urlBase}'
};
</script>
Then your "pure" Javascript code can look to window.appConfig
to get critical information. Obviously this would get to be a mess if you needed a whole lot of stuff.
This is particularly easy when your pages are built via some templating system in your server-side environment. That way, you only have to set the script tag up in one place (or a small number of places; the templates in other words) and all the pages get it automatically.
(edited to eliminate weird variable declaration)
You can easily pull down XML files using something like jquery (http://think2loud.com/reading-xml-with-jquery/).
However, I'd like to pose whether environment specific client-side javascript code is really a good idea. Seems like any environment specific (ie. qa, uat, production I assume) should be handled on the server and the client should be environment agnostic
I'd recommend using YCB. Here is an example how to use it: https://github.com/yahoo/ycb/blob/master/examples/simple/app.js
精彩评论