Good structuring of JavaScript in a project?

时间秒杀一切 提交于 2019-12-22 06:40:57

问题


So, I'm fairly done with the JS in my website now. It involves jQuery (and as such a .ready init) The page has two parts, the upper is mainly Google Maps and the lower is input forms.

All of this is currently in one .js, functions, inits, iterations, all of it. It's well structure and all that, everything is properly done.

My question is however: What is a good structure? Should I be putting the upper half in one file and the lower in another? Or should I put all the needed initializations under the .ready() and place all functions in another file? Or should I keep everything in an ever growing file?


回答1:


From a performance perspective, supplying all your JS in a single file to the browser as suggested by the other answers is sensible. However, having your code built that way is not, each "class" should be in a separate file, splitting things up in to entities and a control file or two to handle the actual page calls - the same as in any other language. These can then be combined in to one file for supply either in advance, or dynamically - preferably also minimized.




回答2:


Keeping the script calls to a minimum improves processing time -- each script include is a round-trip that adds time. So -- personal preference, as long as you don't care about page load times.

Yahoo's Best Practices for Speeding Up Your Web Site starts off with Minimize HTTP Requests:

80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages.

One way to reduce the number of components in the page is to simplify the page's design. But is there a way to build pages with richer content while also achieving fast response times? Here are some techniques for reducing the number of HTTP requests, while still supporting rich page designs.

Combined files are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet. Combining files is more challenging when the scripts and stylesheets vary from page to page, but making this part of your release process improves response times.




回答3:


Personally, I prefer to keep all code in a single file, so the browser has to fetch only one file and not two/three/four/whatever.

But I think it's up to personal preference.



来源:https://stackoverflow.com/questions/4256887/good-structuring-of-javascript-in-a-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!