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 form开发者_如何学编程s.
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?
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.
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.
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.
精彩评论