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($开发者_Python百科_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
<?php
$site_name = basename($_SERVER['SCRIPT_NAME'], ".php");
echo "
<script type=\"text/javascript\" src=\"$site_name.js\"></script>
";
?>
Of course, there's other ways of doing it too. You might consider a framework like CodeIgniter, CakePHP, or Drupal to manage your files.
I would recommend keeping everything in one javascript tag, and (if the javascript files are large enough) move them to separate files instead of inline. Other than that, I would consider it a better solution than making the browser process javascript it doesn't need. Just remember you did this when the javascript can't find a function ;)
精彩评论