You would only be able to do this if the PHP interpreter is configured to run on *.js files, which by default it won't be. Quite honestly, I wouldn't recommend this behavior.
What I'd do instead is something like this (This method can be used for CSS files, too.):
<script type="text/javascript" src="js.php"></script>
js.php
<?php
//GZIP the file and set the JavaScript header
ob_start("ob_gzhandler");
header("Content-type: text/javascript");
//Set a JavaScript variable based on PHP work
echo 'var logged_in_user = "'.$_SESSION['username'].'";';
//Require an external script
require_once($_SERVER['DOCUMENT_ROOT']."/path/to/jquery.js");
?>
//More Javascript functions and code here
$(document).ready(function() {
$('#mydiv').tipsy();
});
<?php
//Flush the output buffer
ob_end_flush();
?>
I personally do this for many reason.
I have many jQuery files I want to include, but I don't want my browser doing 5+ HTTP requests. Including them all in one file means less HTTP requests.
GZIP! I'm significantly reducing the size of the file be transferred and that speeds things up for the visitor.
It's a central location to add, remove, or modify my JavaScript for the whole site. I can even use $_GET
checks to make certain scripts conditional based on how I wrote the <script>
tag.
For example, <script type="text/javascript" src="js.php?var=1"></script>
. I can then check $_GET['var']
within the js.php file.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…