Cordova应用程序与本地Javascript文件 - 许多文件或只有一个?

时间:2016-11-25 08:05:11

标签: javascript cordova minify

我正在构建一个Cordova移动应用程序,我正在制作的自定义脚本都在应用程序包的本地内部,我担心性能。 这些文件可以很多,比如每个大的命名空间变量都在一个单独的文件中,或者我应该将它们全部放在一个文件中吗?

就像我说的那样,所有这些文件都将在本地呈现,而不是在服务器上呈现,我担心性能。

2 个答案:

答案 0 :(得分:2)

如果没有首先显示存在性能问题并确定问题的确切位置,请不要优化性能。首先是可维护性代码。我会将你的JavaScript文件分开。

答案 1 :(得分:0)

Your app should have some sort of build process. There are lots of tools that help automate this process (gulp, grunt, etc.) but you can get by with simple npm scripts as well. How you create a build process is not the point here. The benefits, however, are many:

  1. You can develop your app using multiple small files. If you have good organization and consistent naming practices, these files will be easier to maintain than one large file.

  2. You can build appropriate debug and release versions of your app from those files.

    a. If you want the files to be bundled into one large file, you can use a packer like Browserify, Webpack or JSPM. Then, depending on the options you pass, your debug version can include the necessary sourcemaps to make debugging easy.

    b. You might also want to use other tools, such as a minifier for your JS code, or image optimizer for your icons.

  3. You can use the well-established module patterns to create modular code that doesn't pollute the global namespace (if you use something like Browserify, JSPM, etc.). This means you can do something like this:

    // file: say.js
    module.exports = {
        hello: function hello() {
            alert("hello");
        },
        goodbye: ...,
        ...
    };
    
    // file: index.js
    var say = require("./say.js");
    say.hello();
    say.goodbye();
    

Do none of the above because it will be "faster", though, because the difference when loading a single file vs loading multiple files is almost certainly negligible and on the order of milliseconds. Your user simply will not notice unless you've got a huge number of files. And should it become an issue, it's easy to make your build process generate a release version with everything bundled up into one large file without sacrificing maintainability.

Do do the above to make your workflow easier. Editing a single file with a hundred thousand lines is no fun -- you don't want to do that, trust me.