2

What is the best way to add dynamic content to JavaScript, especially configuration settings?

A couple possibilities are:

  1. Place the content in a dynamically generated file (e.g., JSP, PHP, etc.) rather than a JavaScript file, perhaps using an object literal.
  2. Request the content from the server via ajax as JSON.
5
  • "Use a JavaScript literal." Huh? Commented May 17, 2011 at 15:59
  • 2
    It depends. I prefer static libraries and then fetch dynamic data using AJAX when necessary. Why exactly would you need dynamic JavaScript files? Commented May 17, 2011 at 16:02
  • I have several reasons to use dynamically generated JavaScript. One is to set the options for a jQuery plug-in (jqGrid specifically), which usually change each time a page is viewed. Another reason is to accommodate internationalization messages. Commented May 17, 2011 at 19:34
  • @T.J. JavaScript literal: dyn-web.com/tutorials/obj_lit.php Commented May 17, 2011 at 19:35
  • @Jack: Okay, so that's a dynamically-generated thing then, exactly like option #1. You can see how one would be confused. Commented May 17, 2011 at 20:48

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

2

We do not generate dynamic JavaScript.

We do generate dynamic HTML

Then use progressive enhancement to enhance the HTML with JavaScript. If you want to store data, store it in HTML5 data- attributes on relevant HTML elements.

Alternatively you write a Web Service and query it with AJAX to get dynamic data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.