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


i have ajax-enabled crud application. if display record database shows record's values each column, including primary key.

for ajax actions tied buttons on page able set calls printing id directly onclick functions when rendering html server-side. example, save changes record may have button follows, '123' being primary key of record.

<button type="button" onclick="saverecord('123')">save</button> 

sometimes have pages javascript generating html , javascript. in of these cases primary key not naturally available @ place in code. in these cases took shortcut , generate buttons so, taking primary key place happens displayed on screen 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 works, seems wrong drive database queries based on value of text purpose user consumption rather method consumption. solve adding series of additional parameters various methods usher primary key along until needed, seems clunky.

the natural way me solve problem situate javascript lives in external files, in <head> of page. in way generate custom javascript methods without having pass around many parameters.

other readability, i'm struggling see benefit there storing javascript externally. seems makes weak marriage between html/dom , javascript more distant.

i've seen people suggest leave javascript external, set various "custom" variables on page itself, 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 better putting javascript on page in first place? there html , javascript still dependent on each other.

  • performance (due browser caching)
  • separation of concerns - html/css/javascript should separate. makes working them easier. know locate areas, plus other developers can work on likes of html, css , javascript independently.
  • reuse - can include source file in multiple locations/projects without duplicating code.

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -