Nicolo Verrini
Nicolo Verrini

Reputation: 33

Javascript compressor problem

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

Upvotes: 3

Views: 283

Answers (4)

acme
acme

Reputation: 14856

If using YUI Compressor: You can trick the compression by using /*!comment blocks surrounding your PHP code:

Using the YUI Compressor on JavaScript files containing PHP

Upvotes: 0

cllpse
cllpse

Reputation: 21727

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.

Upvotes: 3

Sune Rievers
Sune Rievers

Reputation: 2754

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.

Upvotes: 0

Mike Atlas
Mike Atlas

Reputation: 8231

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.

Upvotes: 4

Related Questions