php


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


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

Related Links

Converting Python ByteArray -> Php [duplicate]
Update MySQL with .html() in JQUERY/AJAX
InstantClick disables form submit
HTTP request failed in PHP Bad Request
PHP - File get contents and proper encoding
Error (check link)
CI - Help Inserting Multiple Select Form with each having Multiple Selected Options
How to output variable inside an object in PHP
How $_POST value missing unless field specified within model rules?
Addind DISCUS commenting system to your site
Incorrectly executed script for the selection of IP addresses
How to calculate time range between sale start and sale end including the second?
Dynamically add columns in an existing table on the fly in CakePHP 3
Custom post query in single post type
PHP check value against multiple values with OR-operator
Incorrect table definition; there can be only one auto column and it must be defined as a key Codeigniter

Categories

HOME
xpath
rust
visual-studio
shinyapps
paypal-ipn
writefile
activemq
command-prompt
nsview
ios-simulator
odata
impala
kurento
port
hspi
eddystone
gtk
siesta
twitter-oauth
alljoyn
responsivevoice
corona
android-5.1.1-lollipop
exe
cocos2d-android
exec-maven-plugin
jaspersoft-studio
xsl-fo
wsf
spyder
gitkraken
weex
hdl
amazon-sns
eclipse-emf
sap-lumira
code-climate
nic
progid
seafile-server
netstat
love2d
ms-solver-foundation
nanogallery
hidden-markov-models
praat
newtons-method
contactless-smartcard
fluid-mac-app-engine
audio-converter
spongycastle
cordova-ios
gestures
entropy
spring.net
gtk#
nivo-slider
fitbit
rational-performance-test
apache-pig-grunt
highlighting
urbit
xcopy
mercurial-extension
univocity
cfwheels
mixins
alwayson
relational-model
phpredis
fuseesb
jcheckbox
adwords-apiv201402
inequality
quantify
rpg
senchatouch-2.4
nodeload
air-native-extension
ember-table
sly-scroller
arel
uitextfielddelegate
autosize
type-safety
fragment-identifier
jquery-1.4
airprint
aggregator
resharper-5.0
browser-based
dm
firephp
regioninfo
remote-working

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App