问题描述
管理中大型 JavaScript 应用程序的标准做法有哪些?我关心的是浏览器下载速度以及开发的简易性和可维护性.
What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.
我们的 JavaScript 代码大致命名空间"为:
Our JavaScript code is roughly "namespaced" as:
var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and variables */
},
orders: {
/* 100's of functions and variables and subsections */
}
/* etc, etc for a couple hundred kb */
}
目前,我们有一个(未打包、未剥离、高度可读的)JavaScript 文件来处理 Web 应用程序上的所有业务逻辑.此外,还有 jQuery 和几个 jQuery 扩展.我们面临的问题是永远在 JavaScript 代码中找到任何东西,而浏览器仍然有十几个文件要下载.
At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes forever to find anything in the JavaScript code and the browser still has a dozen files to download.
将一些源"JavaScript 文件编译"成一个最终的压缩 JavaScript 文件是否很常见?还有其他方便的提示或最佳做法吗?
Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices?
推荐答案
我发现对我有用的方法是为每个类使用单独的 JS 文件(就像在 Java、C# 和其他中一样).或者,如果您更容易导航,您可以将您的 JS 分组到应用程序功能区域.
The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and others). Alternatively you can group your JS into application functional areas if that's easier for you to navigate.
如果将所有 JS 文件放在一个目录中,则可以让服务器端环境(例如 PHP)遍历该目录中的每个文件并输出 <script src='/path/to/js/$file.js' type='text/javascript'>
包含在所有 UI 页面中的某个头文件中.如果您经常创建和删除 JS 文件,您会发现这种自动加载特别方便.
If you put all your JS files into one directory, you can have your server-side environment (PHP for instance) loop through each file in that directory and output a <script src='/path/to/js/$file.js' type='text/javascript'>
in some header file that is included by all your UI pages. You'll find this auto-loading especially handy if you're regularly creating and removing JS files.
在部署到生产环境时,您应该有一个脚本将它们全部组合成一个 JS 文件并缩小"它以减小大小.
When deploying to production, you should have a script that combines them all into one JS file and "minifies" it to keep the size down.
这篇关于管理和部署大型 JavaScript 应用程序的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!