I would like to know when I should include external scripts or write them inline with the html code, in terms of performance and ease of maintenance.
What is the general practice for this?
Real-world-scenario - I have several html pages that need client-side form validation. For this I use a jQuery plugin that I include on all these pages. But the question is, do I:
- write the bits of code that configure this script inline?
- include all bits in one file that's share among all these html pages?
- include each bit in a separate external file, one for each html page?
Thanks.
Externalizing javascript is one of the yahoo performance rules: http://developer.yahoo.com/performance/rules.html#external
While the hard-and-fast rule that you should always externalize scripts will generally be a good bet, in some cases you may want to inline some of the scripts and styles. You should however only inline things that you know will improve performance (because you've measured this).
Three considerations:
On the point of keeping JavaScript external:
ASP.NET 3.5SP1 recently introduced functionality to create a Composite script resource (merge a bunch of js files into one). Another benefit to this is when Webserver compression is turned on, downloading one slightly larger file will have a better compression ratio then many smaller files (also less http overhead, roundtrip etc...). I guess this saves on the initial page load, then browser caching kicks in as mentioned above.
ASP.NET aside, this screencast explains the benefits in more detail: http://www.asp.net/learn/3.5-SP1/video-296.aspx
i think the specific to one page, short script case is (only) defensible case for inline script
I would take a look at the required code and divide it into as many separate files as needed. Every js file would only hold one "logical set" of functions etc. eg. one file for all login related functions.
Then during site developement on each html page you only include those that are needed. When you go live with your site you can optimize by combining every js file a page needs into one file.
Actually, there's a pretty solid case to use inline javascript. If the js is small enough (one-liner), I tend to prefer the javascript inline because of two factors:
jQuery
you can either use thelive
ordelegate
methods to circumvent this, but I find that if the js is small enough it is preferrable to just put it inline.