views:

53

answers:

3

Hi to everyone, I have a problem I would like to compress all my javascript, but inside of my javascript code I use php stuff... like php if, php variables. How can I manage that? Thank you so much

+4  A: 

If your PHP is outputting JavaScript, you'll need to break it up into two parts:

  • JavaScript that you want to compress
  • JavaScript that contains the data from your PHP output. This part you can't compress, but at least it can be called from the compressed JavaScript.
Mike Atlas
A: 

You could compress the javascript on the fly, using zlib. Most browsers should be able to handle that. However, I don't think it will be worth the extra cpu cycles on the server.

Otherwise, you should do what Mike Atlas says, and partition your dynamic javascript from your static, and only compress the latter.

Sune Rievers
+3  A: 

To save yourself some trouble, create an object to hold the data your PHP script echo's out. Like so:

var dataPhpEchosOut = {
    foo: <?php echo $foo; ?>,
    bar: <?php echo $bar; ?>
    etc.
};

And use the data object like so:

alert(dataPhpEchosOut.foo + " - " + dataPhpEchosOut.bar);

Now you've got some separation; you can compress the rest of you JavaScript code.

roosteronacid