Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages to putting your Javascript in a .php file?

Tags:

javascript

php

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?

like image 955
Mark Biek Avatar asked Jun 15 '09 19:06

Mark Biek


2 Answers

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").";";


?>
like image 193
TJ L Avatar answered Oct 21 '22 20:10

TJ L


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)
like image 43
hannson Avatar answered Oct 21 '22 20:10

hannson