What benefits are there to storing Javascript in external files vs in the <head>?

Posted by RenderIn on Stack Overflow See other posts from Stack Overflow or by RenderIn
Published on 2010-04-27T18:37:32Z Indexed on 2010/04/27 18:53 UTC
Read the original article Hit count: 276

Filed under:
|

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.

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.

<button type="button" onclick="saveRecord('123')">Save</button>

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:

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

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.

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 <head> of the page. In that way I could generate custom Javascript methods without having to pass around as many parameters.

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.

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:

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

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about subjective