Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dynamic external javascript files?

I am thinking about how some online services create dynamic JavaScript files. These files have the .js extension, but their content is not static. I found a sample file here. It seems that this script is generated with a higher level programming language. I think it is done with PHP or something similar, but I am not sure, and I have not found any documentation about this topic.

Is there any well known way to create these kind of dynamic JavaScript files?

like image 828
Patartics Milán Avatar asked May 17 '13 15:05

Patartics Milán


1 Answers

Consider carefully whether generating a dynamic JS file is necessary at all. Instead of generating dynamic JS, you can often simply inject static script(s) and use separate JSON to support dynamic configuration into your page.

If you view source on this (or about any) StackOverflow page you'll see that they're using this same pattern: Static external .js files that reference a separate centralized chunk of JSON for configuration. That JSON is what provides dynamism.

View source and look for this:

StackExchange.init({...

Most server side languages make it trivial to serialize an object to JSON so you can inject it into your page.

Here's ten reasons utilizing external static js files is preferable:

  1. Cached
  2. Code colored
  3. Syntax checked
  4. Separation of concerns
  5. Reusable
  6. Easier to read.
  7. One less layer of abstraction
  8. Can serve minified and obfuscated
  9. Avoids string parsing on every request
  10. StackOverflow and all the cool kids are doing it (hey, I promised 10 reasons.)

More info here: http://www.bitnative.com/2013/10/06/javascript-configuration-object-pattern/

like image 173
Cory House Avatar answered Sep 18 '22 11:09

Cory House