How to create dynamic external javascript files?

别等时光非礼了梦想. 提交于 2019-12-22 06:56:02

问题


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?


回答1:


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/




回答2:


That depends on whether you want to generate files or return data. Generating files would be done with something like file_put_contents. Alternatively you could have a .js file in a folder with a .htaccess file that tells you to execute it as php, allowing you to simply generate the script on the fly based on session, get, or post parameters.




回答3:


You can use any server-side language to create dynamic javascript files, javascript files don't need to end with .js. If you really want your files to end with .js you'll need to edit your server settings to also process .js files as for instance PHP files.

You can also use server code to generate inline javascript.

But be careful when generating javascript files, it can become very complex when you are mixing two programming languages



来源:https://stackoverflow.com/questions/16612639/how-to-create-dynamic-external-javascript-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!