I want to use the YUI Compressor on JavaScript files that contain PHP code like for example:
<?php $include 'headerDefinitions.js.php'; ?>
function hello(name) {
alert('Hello ' + name);
}
hello('<?= $_GET["name"] ?>');
This obviously throws some errors when running through yui compressor like this:
java -jar yui-compressor.jar --type js -o target-file.js.php source-file.js.php
because the compressor assumes even the PHP part is JavaScript. Is there a way to compress the JavaScript while preserving and ignoring the PHP parts? So that the example above results in:
<?php $include 'headerDefinitions.js.php'; ?>fun开发者_运维技巧ction hello(a){alert('Hello '+a)}hello('<?= $_GET["name"] ?>');
It won't work. You should define all of your functions in plain .js files and then any dynamic values or function calls be on your PHP page. Aside from allowing compression, it will allow your .js files to be cached properly by the browser.
To answer myself:
jiggys answer to separate JavaScript from PHP is probably the most clean one and should be followed when possible. But sometimes it's not possible. In my case I can't divide PHP and JavaScript without spending a huge amount of time (it's an old and big project).
Anyway, the YUI Compressor is not stripping JavaScript comments that start with /*!
so the key is to surround PHP code in a comment block like this:
/*!
<?php $include 'headerDefinitions.js.php'; ?> */
function hello(name) {
alert('Hello ' + name);
}
hello('<?= $_GET["name"] ?>');
That's all. There will be an empty comment block when viewed in the browser, but it can be neglected or filled with some copyright info.
PHP code within JavaScript strings need no further attention as they (obviously) remain untouched during the compressing process:
var myString = '<?= $_GET["name"] ?>';
does not need to be modified. You only have to take care not to use single or double quotes for both the JavaScript string declaration and strings in the PHP code.
精彩评论