JS - one huge file or many small files? - where to draw a line?

前端 未结 5 1722
悲哀的现实
悲哀的现实 2021-01-04 04:36

Is there a good rule of thumb as to how big (in size) a JS file should be - that if it grows bigger than this it\'s good idea to split it into smaller files?

相关标签:
5条回答
  • 2021-01-04 04:46

    Develop in as many files as you want. Organize your code to keep development manageable.

    Then, when you deploy, ship a minified/combined version of the code using a tool like Google Closure

    This is what jQuery does. They ship one file, but the actual source code is much more organized.

    0 讨论(0)
  • 2021-01-04 04:47

    All my JS files - one per function plus the libraries - are in one folder outside the public directory, the prioritary ones start with one or two underscores. In my index page, a PHP script from a static server is called. It checks whether or not the compressed JS file exists. If it does not, a scandir is performed on the JS directory, and each file is included in a buffer, then compressed, and put into a single file. And it outputs the content of this file.

    If I change/add/delete a js file, all I have to do is delete the compressed file, and it will be recreated at the next load.

    The advantage here is that you have a single and optimized http request for the javascript, and still you can divide your scripts in as many files as you wish. The file creation process - which can be heavy - is not used each time the page loads but only when the file is missing. This method is good when like me you use it with an application which never reloads, or doesn't need to load specific functions for specific pages, although there would be plenty of workarounds.

    0 讨论(0)
  • 2021-01-04 04:52

    The same size as any other languages (never more than a few hundred lines), and the concat and minify at runtime (using the Closure compiler or the Yahoo libs or whatnot) is what we do.

    0 讨论(0)
  • 2021-01-04 05:04

    More files = More HTTP Requests = Slower website

    0 讨论(0)
  • 2021-01-04 05:04

    Less files = less clean code = slower coding. Cost more than bandwidth.

    Edit: if you really want to, you may have tool to merge them after you code of course.

    0 讨论(0)
提交回复
热议问题