Donald T
Donald T

Reputation: 10667

Best practices for dynamically generating JavaScript

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.

Upvotes: 2

Views: 5652

Answers (2)

Raynos
Raynos

Reputation: 169411

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.

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328624

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.

Upvotes: 12

Related Questions