i have a javascript file about开发者_如何学运维 6000+ lines of codes created by myself. Now it has functions for different sections of my site.. Now what i want to ask is that should i use that large file or divide it in parts for respective sections and call it in respective section.
I would suggest using 1 large one, as that requires only 1 http request. And with the right server setup it is only loaded once as it becomes cached.
It depends on how much the HTTP request cost is Vs. how likely a visitor is to access one of the sections with specific JS Vs. how much bandwidth is saved for the other pages.
If it's just a question of serving the file, then one large one is almost definitely better, particularly if your server has gzip compression turned on (which it should).
However, you might also want to break the file up into smaller parts to improve the readability and maintainability aspects of the code. In such a case you might still want to serve out the entire script in a single request, which you can do with a custom servlet (or other comparable bit of server-side logic) that concatenates all the parts together and sends the result to the client.
Lately, it appears as if the best approach is to split it up into smaller files and load only the needed ones, in parallell, using some kind of JS loader (like Head JS for example; click the link and scroll down to the headline "Combining scripts" to read more about the performance difference).
Another possible loader to use would be RequireJS.
精彩评论