是否值得将一个大的JavaScript文件拆分成许多较小的文件?

huangapple go评论75阅读模式
英文:

Is it worth spliting up a large JavaScript file into many smaller one?

问题

我目前正在开发一个游戏,需要为在单个HTML页面上进行游戏的许多函数。目前,我已经在一个JavaScript文件中实现了所有函数,但是这个文件变得非常庞大,看起来不太"整洁",也不太"易于阅读"。

我在考虑也许应该为一组函数创建单独的文件。这可以解决上述问题,但也意味着需要加载更多的js文件,尽管网页引用的整体代码仍然相似。

我不确定是否采取第二种方法是值得的。在做出决策时,我需要考虑哪些因素,以及两种决策的后果是什么?

目前,我把所有的js代码都放在一个文件中。

英文:

I am currently working on a game where I need to define many functions for the game that is played on a single HTML page. Currently, I have implemented all functions on one JavaScript file however this file is getting very large and doesn't look as "neat" or as "easy to read".

I am thinking that maybe I should have a file each for a set of functions. This fixes the above problem but also means that there will be a lot more js files to load, although the overall code being referenced by the webpage is still similar.

Im not sure if the second approach is worth taking. What factors do I need to consider when making a decision and what are the consequences of both decisions?

Currently have all js code on one file.

答案1

得分: 4

在拥有大量小型脚本文件时需要考虑的一个重要问题是,如果您的Web服务器使用HTTP 1.1,那么同时传输的文件数量有一个硬性限制。如果文件很多,如果客户端的延迟高,应用程序的完全加载可能需要很长时间。

(如果您的Web服务器使用HTTP/2,则不存在此限制;许多小文件可以正常工作,并且可以与<script type="module">一起使用。)

一种常见的方法是出于可读性考虑,将代码写在许多不同的文件中,但使用构建系统,例如Webpack,将所有这些文件转换为单个更大的捆绑包(或少数捆绑包)以供客户端下载。无论服务器的网络协议如何,捆绑包都将正常工作。此外,拥有构建过程(任何构建过程)对于许多其他方面都很有帮助,例如使用Babel将新语法转译为旧语法和使用缩小来减少需要传输的字节数。

英文:

A big issue to consider when having lots and lots of small script files is that, if your web server uses HTTP 1.1, there's a hard limit to how many files can be being transferred at once. If there are many files, it could take a long time for an app to fully load if the client's ping is bad.

(If your webserver uses HTTP/2, no such limit exists; lots of tiny files can work just fine, and can be used in combination with &lt;script type=&quot;module&quot;&gt;.)

A common approach is to write in many different source files for readability's sake, but to use a build system like Webpack to take all of those files and transform them into a single larger bundle (or few) for download by clients. Bundles will work well no matter the network protocol of your server. Also, having a build process (any build process) is helpful anyway for many other things, such as Babel to transpile down new syntax into old syntax and minification to reduce the number of bytes that need to be transferred.

huangapple
  • 本文由 发表于 2023年2月24日 11:45:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75552441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定