What benefits are there to storing Javascript in external files vs in the <head>?
<p>I have an Ajax-enabled CRUD application.  If I display a record from my database it shows that record's values for each column, including its primary key.</p>

<p>For the Ajax actions tied to buttons on the page I am able to set up their calls by printing the ID directly into their onclick functions when rendering the HTML server-side.  For example, to save changes to the record I may have a button as follows, with '123' being the primary key of the record.</p>

<pre><code>&lt;button type="button" onclick="saveRecord('123')"&gt;Save&lt;/button&gt;
</code></pre>

<p>Sometimes I have pages with Javascript generating HTML and Javascript.  In some of these cases the primary key is not naturally available at that place in the code.  In these cases I took a shortcut and generate buttons like so, taking the primary key from a place it happens to be displayed on screen for visual consumption:</p>

<pre><code>...
&lt;td&gt;Primary Key: &lt;/td&gt;
&lt;td&gt;&lt;span id="PRIM_KEY"&gt;123&lt;/span&gt;&lt;/td&gt;
...
&lt;button type="button" onclick="saveRecord(jQuery('#PRIM_KEY').text())"&gt;DoSomething&lt;/button&gt;
</code></pre>

<p>This definitely works, but it seems wrong to drive database queries based on the value of text whose purpose was user consumption rather than method consumption.  I could solve this by adding a series of additional parameters to various methods to usher the primary key along until it is eventually needed, but that also seems clunky.</p>

<p>The most natural way for me to solve this problem would be to simply situate all the Javascript which currently lives in external files, in the <code>&lt;head&gt;</code> of the page.  In that way I could generate custom Javascript methods without having to pass around as many parameters.</p>

<p>Other than readability, I'm struggling to see what benefit there is to storing Javascript externally.  It seems like it makes the already weak marriage between HTML/DOM and Javascript all the more distant.</p>

<p>I've seen some people suggest that I leave the Javascript external, but do set various "custom" variables on the page itself, for example, in PHP:</p>

<pre><code>&lt;script type="text/javascript"&gt;
var primaryKey = &lt;?php print $primaryKey; ?&gt;;
&lt;/script&gt;
&lt;script type="text/javascript" src="my-external-js-file-depending-on-primaryKey-being-set.js"&gt;&lt;/script&gt;
</code></pre>

<p>How is this any better than just putting all the Javascript on the page in the first place?  There HTML and Javascript are still strongly dependent on each other.</p>

<p></p>
