What is the best way to add dynamic content to JavaScript, especially configuration settings?
A couple possibilities are:
- Place the content in a dynamically generated file (e.g., JSP, PHP, etc.) rather than a JavaScript file, perhaps using an object literal.
- Request the content from the server via ajax as JSON.
I suggest to put as much JavaScript as possible in a static resource (so the browser can cache that) and just generate the smallest possible dynamic part. Often that’s just a few variable assignments.
This approach saves network bandwidth, it makes the code generation more robust, and you can test the static JavaScript as usual.