Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I do two things:</p> <ol> <li>I put all my site's Javascript in one or more files;</li> <li>I include that file or files on every page that uses any Javascript;</li> <li>Those files are cached effectively such that they are only ever downloaded once (until they change); and</li> <li>Pages call the functions they need from those external files.</li> </ol> <p>If your site is one page then put it inline.</p> <p>If your site is 20 pages and they all use a little bit of Javascript, put it all in one files, include it on every page and call the functions with inlien Javascript as necessary in each file.</p> <p>I write about this and more in <a href="http://www.cforcoding.com/2009/05/supercharging-javascript.html" rel="nofollow noreferrer">Supercharging Javascript in PHP</a>. Sure it's PHP-specific but the principles are universal.</p> <p>Basically every extra HTTP request is a problem. So if you have 20 pages each with a different Javascript file then that's a problem, even if those files are small. It's better to combine all that Javascript in one file, download it just once (with effective caching) and just use what you need.</p> <p>To give you an example. External JS file contains:</p> <pre><code>function delete_user(evt) { ...} function suspend_user(evt) { ... } function unsuspend_user(evt) { ... } </code></pre> <p>One of your Web pages contains:</p> <pre><code>$(function() { $("#delete").click(delete_user); $("#suspend").click(suspend_user); $("#unsuspend").click(unsuspend_user); }); </code></pre> <p>This way you get an external JS that contains all your site's Javascript but none of it is actually used. Use comes from inline code in the pages. This way there is no overhead of having the larger JS file.</p> <p>Whatever you do, don't put in ALL initialization in your Javascript file. I once made this mistake and put a huge $(function() { ... } function into the external file on the grounds that if the relevant IDs weren't in the page, nothing would happen. There ended up being enough of this code to add nearly half a second to the page load time (and the site wasn't <em>that</em> big).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload