开发者

Magento - HTML minify code causing some javascript not working

开发者 https://www.devze.com 2023-02-04 19:08 出处:网络
I have the below code to remove white space in a Magento site. ob_start(\"htmlcompress\"); function htmlcompress($buffer) {

I have the below code to remove white space in a Magento site.

ob_start("htmlcompress");

function htmlcompress($buffer) {
   $buffer = preg_replace('/\n\r|\r\n|\n|\r|\t| {2}/', '', $buffer);
   return $buffer; 
}

It works well, however in some areas where inline javascripts are used, the scripts stopped working. Example, in "checkout/onepage/billing.phtml":

<script type="text/javascript">
//<![CDATA[  
$('billing:region_id').setAttribute('defaultValue', "<?php
  echo $this->getAddress()->getRegionId()
?>");
//]]>
</script>

and "giftmessage/inline.phtml" where toogle function disabled; also the "payment/form/cc.phtml" where radio button for payment options.

Not all inline 开发者_JAVA百科scripts got disabled though, for instance, anything start with "var" are working.

How I can improve the compress script to prevent javascript from stop working?

Thanks


You're reinventing work that has already been done.

First there is minify which has PHP classes for performing exactly this operation. Fooman Speedster uses the minify library for Javascript and CSS but misses out the HTML parts, it might be possible to modify this behaviour.

Then there is mod_pagespeed which has it built in, is compiled so runs faster than PHP and works for the entire server so pages from other scripts/sources are affected to. In particular you should be interested in it's whitespace collapse.


Thanks! You code removes ALL spaces though, thus breaking styles too. I am aware of the Fooman Speedster, unfortunately it doesn't work for many clients' shared-servers.

@clockworkgeek, I am aware of the scripts you posted too, similar to Fooman Speedster, they don't work in all shared servers, and though some work but the result is unreliable as it affects some pages, which I guess is similar to the minify script I posted, causing issue to javascript and whitespace. In other case, it causes memory corruption.

My host however is working on getting the mod_pagespeed for the shared servers.


The problem is that is not a code aware regex. You could divide the minify process in two parts. Striping spaces, and striping line breaks.

For example:

$buffer = preg_replace('/^(?!\/{2})(.*)[\n\r|\r\n|\n|\r]/m', '$1', $buffer);

Then just need to remove unnecessary spaces. Like tabs and two or more spaces.

$buffer = preg_replace('/[\t| {2}]/', '', $buffer);

Also, checkout the Fooman Speedster extension.

0

精彩评论

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