Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for dynamically generating JavaScript

Tags:

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.
like image 884
Donald Taylor Avatar asked Apr 20 '26 21:04

Donald Taylor


2 Answers

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.

like image 173
Aaron Digulla Avatar answered Apr 23 '26 08:04

Aaron Digulla


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.

like image 25
Raynos Avatar answered Apr 23 '26 07:04

Raynos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!