tags:

views:

441

answers:

8

I occasionally come across pages where some Javascript is included via a PHP file:

<html>
  <head>
    <script type="text/javascript" src="fake_js.php"></script>
  </head>
  <body onload="handleLoad();">
  </body>
</html>

where the contents of fake_js.php might look something like this:

<?php header('Content-type:  text/javascript') ?>

function handleLoad() {
    alert('I loaded');
}

What are the advantages (or disadvantages) to including Javascript like this?

+1  A: 

There's no benefit for the example you gave above (beyond peculiar deployment scenarios where you have access to .php files and not .js files, which would be insane but not unheard of).

That said, this approach allows you to pass the JS through the php parser - which means you can generate your JS dynamically based on server variables.

DDaviesBrackett
+13  A: 

It makes it easy to set javascript variables from the server side.

var foo = <?=$foo?>

I usually have one php/javascript file in my projects that I use define any variables that need to be used in javascript. That way I can access constants used on the server-side (css colors, non-sensitive site properties, etc) easily in javascript.

Edit: For example here's a copy of my config.js.php file from the project I'm currently working on.

<?php
require_once    "libs/config.php";
if (!function_exists("json_encode")) {
    require_once "libs/JSON.php";
}
header("Content-type: text/javascript");
echo "var COLORS = ". json_encode($CSS_COLORS) .";\n";
echo "var DEBUG = ". ((DEBUG == true) ? "true" : "false").";";


?>
tj111
Interesting. That's a nice way to handle that.
Mark Biek
Of course, the drawback to this approach is you've got to trust that the output is syntactically correct, though sticking to something which utilizes json_encode would help.
altCognito
It also works nicely for CSS files.
Rob Allen
A: 

Advantage (not PHP specific - I used this technique in EmbPerl and JSP) would be the ability to dynamically generate or tweak/customize the JavaScript code on the server side.

An example usage would be population of an array based on the contents of a DB table. Or application of localization techniques.

DVK
A: 

seamless version control without the need to modify client templates

<script src='script.php'></script>

<?php
 include('correct_script');
?>
Causas
+6  A: 

If you don't need it, don't use it:

The first thing you need to keep in mind is YAGNI. You Ain't Gonna Need It. Until a certain feature, principle, or guideline becomes useful and relevant, don't use it.

Disadvantages:

  • Added complexity
  • Slower than static files.
  • Caching problems (server side)
  • Scalability issues (load balancers offload static files from the heavy PHP/Apache etc processes)

Advantages:

  • User specific javascript - Can be achieved by initializing with the right variables / parameters in the <head> </head> section of the HTML
  • Page specific javascript - JS could also be generalized to use parameters
  • JSON created from database (usually requested via AJAX)

Unless the javascript is truely unique (i.e. JSON, parameters/variables) you don't gain much. But in every case you should minimize the amount of JS generated on the server side and maximize the amount of code in the static files. Don't forget that if it's dynamic, it has to be generated/downloaded again and again so it's not wanted for it to be a heavy process.

Also:

  • This could also be used to minimize the amount of server configuration (for example if the web server doesn't serve file.js with the correct content type)
Hannson
if you need dynamic data there are better ways today. json? xmlhttp?no need for those beasts (can anyone spell 'let the browser cache the JS files'?)
elcuco
What exactly are the alternatives? Flex, Silverlight or some other proprietary plug-in?
Hannson
+1  A: 

Agree with tj111. Apart from what tj mentioned, I also found php-generated javascripts a great weapon to fight the browser's caching tricks. Not that long ago I was cursing the whole javascript for its being constantly cached by the browser. Refreshing the page helped me not, had to clear the whole cache in order to force the browser to reload the javascript files. As soon as I built a php wall in front of my javascripts:

fake_js.php:

<?php 

header('Content-type:  text/javascript') 
include('the_real_javascript.js');

?>

A fresh new javascript would always show up at the client side. However this approach is obviously only good in the development phase, when it can save the developer quite some headache to have the correct javascript loaded in the browser. Of course when connecting to localhost, the penalty of repeatedly loading the same file is not as big.

In a live web application/site client-side caching is welcome to reduce network traffic and overall server load.

Peter Perháč
A: 

If you don't have full server access and can't turn on gzip encoding then it's pretty useful to put the following in your javascript file (note: will need to be renamed to file.js.php or parsed as PHP through .htaccess directive):

<?php
ob_start( 'ob_gzhandler' );
header("Content-type: text/javascript");
?>
// put all your regular javascript below...

You could also use it for better cache control, visitor tracking, etc in lieu of server-controlled solutions.

DisgruntledGoat
A: 

Absolutely none, IMHO. I use a js framework that I wrote to handle the setting of whatever server-side variables I need to have access to. It is essentially the same as embedding PHP in JavaScript, but much less ambiguous. Using this method allows you to also completely separate server-side logic and html away from javascript. This results in much cleaner, more organized and lowly-coupled modular code.

You could do something like this in your html:

<script type="text/javascript">

registry = {
    myString : '<?php echo $somePhpString; ?>',
    myInt    : <?php echo $somePhpInteger; ?>
}

</script>

And then do something like this in your js:

if (registry.myInt === 1) {
    alert(registry.myString);
}
Tres