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

前端 未结 5 1721
悲哀的现实
悲哀的现实 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: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.

提交回复
热议问题