tags:

views:

754

answers:

8

Do you localize your javascript to the page, or have a master "application.js" or similar?

If it's the latter, what is the best practice to make sure your .js isn't executing on the wrong pages?

EDIT: by javascript I mean custom javascript you write as a developer, not js libraries. I can't imagine anyone would copy/paste the jQuery source into their page but you never know.

A: 

Personally, I try to include several Javascript files, sorted by module (like YUI does). But once in a while, when I'm writing essentially a one-liner, I'll put it on the page.

Max Lybbert
A: 

Best practice is probably to put it on Google's servers.

(Depends what you mean by "your" javascript though I suppose :)

Alastair
i mean code you write, not code in libraries.
Kyle West
Is it possible that the user's connection to google's local server would be significantly faster than to your webserver? It's possible this could save bandwidth and speed up your page. (no vote up because it's not answering the question)
Dean
+5  A: 

Putting all your js in one file can help performance (only one request versus several). And if you're using a content distribution network like Akamai it improves your cache hit ratio. Also, always throw inline js at the very bottom of the page (just above the body tag) because that is executed synchronously and can delay your page from rendering.

And yes, if one of the js files you are using is also hosted at google, make sure to use that one.

Tim Merrifield
Excellent suggestion! Our application has made it a best practice to put as much javascript into included js files as possible, as we have a high percentage of users expected to dial-in via 56K modems.
Ogre Psalm33
Thanks! I think for most devs throwing everything into one file seems like a horrible practice. But sometimes performance outweighs code cleanliness.
Tim Merrifield
+4  A: 

Here's my "guidelines". Note that none of these are formal, they just seem like the right thing to do.

All shared JS code lives in the SITE/javascripts directory, but it's loaded in 'tiers'

For site-wide stuff (like jquery, or my site wide application.js), the site wide layout (this would be a master page in ASP.net) includes the file. The script tags go at the top of the page.

There's also 'region-wide' stuff (eg: js code which is only needed in the admin section of the site). These regions either have a common layout (which can then include the script tags) or will render a common partial, and that partial can include the script tags)

For less-shared stuff (say my library that's only needed in a few places) then I put a script tag in those HTML pages individually. The script tags go at the top of the page.

For stuff that's only relevant to the single page, I just write inline javascript. I try to keep it as close to it's "target" as possible. For example, if I have some onclick js for a button, the script tag will go below the button.

For inline JS that doesn't have a target (eg: onload events) it goes at the bottom of the page.


So, how does something get into a localised library, or a site-wide library?.

  • The first time you need it, write it inline
  • The next time you need it, pull the inline code up to a localised library
  • If you're referencing some code in a localized library from (approximately) 3 or more places, pull the code up to a region-wide library
  • If it's needed from more than one region, pull it up to a site-wide library.

A common complaint about a system such as this, is that you wind up with 10 or 20 small JS files, where 2 or 3 large JS files will perform better from a networking point of view. However, both rails and ASP.NET have features which handle combining and caching multiple JS files into one or more 'super' js files for production situations.

I'd recommend using features like this rather than compromising the quality/readability of the actual source code.

Orion Edwards
Agreed. There are other ways to improve performance aside from throwing it all into one honkin' file; especially when several pages use only a handful of functions (is it really faster to download a 1MB file instead of 3 2KB files? how about after GZIPping the smaller files, or minifying, etc.).
Max Lybbert
+1  A: 

I try to avoid putting javascript functions on the rendered page. In general, I have an application.js (or root.js) that has generic functionality like menu manipulation. If a given page has specific javascript functionality, I'll create a .js file to handle that code and mimic the dir structure on how to get to that file (also using the same name as the rendered file).

In other words, if the rendered page is in public/dir1/dir2/mypage.html, the js file would be in public/js/dir1/dir2/mypage.js. I've found this style works well for me, especially when doing templating on a site. I build the template engine to "autoload" my resources (css and js) by taking the request path and doing some checking for the css and js equivalents in the css and js directories on the root.

localshred
+2  A: 

Yahoo!'s Exceptional Performance Team has some great performance suggestions for JavaScript. Steve Souders used to be on that team (he's now at Google) and he's written some interesting tools that can help you decide where to put JavaScript.

Greg
A: 

This is something I've been wrestling with, too. I've ended up by using my back-end PHP script to intelligently build a list of required JS files based on the content requested by the user.

By organizing my JS files into a repository that contains multiple files organized by purpose (be they general use, focused for a single page, single section, etc) I can use the chain of events that builds the page on the back-end to selectively choose which JS files get included based on need (see example below).

This is after implementing my web app without giving this aspect of the code enough thought. Now, I should also add that the javascript I use enhances but does not form the foundation of my site. If you're using something like SproutCore or Ext I imagine the solution would be somewhat different.


Here's an example for a PHP-driven website: If your site is divided into sections and one of those sections is calendar. The user navigates to "index.phhp?module=calendar&action=view". If the PHP code is class-based the routing algorithm instantiates the CalendarModule class which is based on 'Module' and has a virtual method 'getJavascript'. This will return those javascript classes that are required to perform the action 'view' on the 'calendar' module. It can also take into account any other special requirements and return js files for those as well. The rendering code can verify that there are no duplicates of js files when the javascript include list is built for the final page. So the getJavascript method returns an array like this

return array('prototype.js','mycalendar.js');

Note that this, or some form of this, is not a new idea. But it took me some time to think it important enough to go to the trouble.

Karim
A: 

If it's only a few hundred bytes or less, and doesn't need to be used anywhere else, I would probably inline it. The network overhead for another http request will likely outweigh any performance gains that you get by pulling it out of the page.

If it needs to be used in a few places, I would put the function(s) into a common external file, and call it from an inline script as needed.

If you are targeting an iphone, try to keep anything that you want cached under 25k.

No hard and fast rules really, every approach has pros and cons, would strongly recommend you check out the articles that can be found on yahoo's developer section, so you can make informed decisions on a case by case basis.

seanb