如何创建动态外部javascript文件? [英] How to create dynamic external javascript files?

查看:130
本文介绍了如何创建动态外部javascript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑一些在线服务如何创建动态JavaScript文件。这些文件具有.js扩展名,但它们的内容不是静态的。我找到一个示例文件 here 。看来这个脚本是用更高级别的编程语言生成的。我认为这是用PHP或类似的东西,但我不确定,我还没有找到关于这个主题的任何文件。



有没有一个众所周知的方式创建这些动态JavaScript文件?

解决方案

请考虑是否需要生成动态JS文件。而不是生成动态JS,您通常可以简单地注入静态脚本,并使用单独的JSON来支持动态配置到您的页面。



如果您查看源或关于任何)StackOverflow页面,您将看到他们使用相同的模式:静态外部.js文件引用单独的集中的JSON块来进行配置。这个JSON是什么提供了动力。



查看源代码并查找:

  StackExchange.init({... 

大多数服务器端语言使得序列化对于JSON,所以你可以将它注入你的页面。



这里使用外部静态js文件的十个原因是更好的:


  1. 缓存

  2. 代码彩色

  3. 语法检查

  4. 分离

  5. 可重复使用

  6. 更容易阅读

  7. 一层抽象层

  8. 可以提供最小化和混淆的

  9. 避免每个请求的字符串解析

  10. StackOverflow和所有酷的孩子都在做(嘿,我答应了10个理由。)

更多信息: http://www.bitnative.com/2013/10/06/javascript-configuration-object-pattern /


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?

解决方案

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/

这篇关于如何创建动态外部javascript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆