开发者

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开发者_如何学运维


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜