I am not sure if this general question is even allowed in here but I try it anyways. I am creating a new site (just for fun and to “train” my skills). I am at a point where I have some lines of javascript code, but the code is not needed on every page.
So I have decided to paste ALL javascripts into a php file (javascript.php) and inside that file I have added following lines:
<?php $site_name = basename($_SERVER['REQUEST_URI'], ".php"); ?>
<?php if ($site_name == "index") { ?>
<script type="text/javascript">
//script 1
</script>
<?php } elseif ($site_name == "index1") { ?>
<script type="text/javascript">
//script 1
</script>
<?php } elseif ($site_name == "index2") { ?>
<script type="text/javascript">
//script 2
</script>
<?php } elseif ($site_name == "index3") { ?>
<script type="text/javascript">
//script 3
</script>
<?php } ?>
It works fine.
But, as I am a coding newbie, I was wondering if this a smart solution? Could you girls and guys tell me your opionion and why it is smart/dumb to do this?
Thanks!
If you have to have separate Javascript includes, I wouldn’t use an IF, since it can get quite large and unmanageable. You could use a switch (same problem, IMO), or just put the JS into separate files and include according to the $site_name:
http://codepad.org/Ha02Uscr
Of course, there’s other ways of doing it too. You might consider a framework like CodeIgniter, CakePHP, or Drupal to manage your files.