Search code examples
javascriptphpzend-framework2minifyview-helpers

Minify InlineScript


In my view scripts I am adding javascript using the view helper inlineScript and echoing it in the footer of my template. I am now attempting to minify the generated html using this solution.

My issue is that I include inline comments (e.g. //this is a comment) throughout my code (as I am a good developer) which is causing all code following to be regarded as comment as well (as all new lines are removed and the following code is placed onto the same line as the inline comment).

How do I extend inlineScript to remove comments and / or minify the code using, for example, mrclay minify?

Something I tried was:

<?php echo preg_replace('#//.*#', '', $this->inlineScript()) ?>

Which causes issues on pages where I have code such as:

jQuery(el).attr('data-toggle', 'popover')
    .attr('data-trigger', 'hover')
    .attr('data-html', 'true')
    .attr('data-content', [
        '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="',
        '//' + location.hostname + '/img/broker-logo/' + el.value,
        '"/>'
    ].join(''))

And, a variation of above,

<?php echo preg_replace('#[\s\t]+//.*#', '', $this->inlineScript()) ?>

Which checks for comments on that don't have anything before it. This raises issues where I have code followed by a comment at the end of the line:

var $el = jQuery('table.hover') //only apply effect to hover tables

which produces the same undesirable result as the original issue.


Solution

  • You can add https://github.com/mrclay/jsmin-php to remove comments and whitespaces (see issue https://github.com/mrclay/minify/issues/581 regarding comments).

    If you are using composer project, you can add jsmin-php to your project next way:

    1 step: Run composer require mrclay/jsmin-php in terminal where your composer.json is located to install a package.

    2 step: Add to your implementation of script minification function the line with JSMin::minify that will remove comments:

    function removeComments(string $code) {
      // $code is variable that contains JS with comments, could be something like
      // $code = 'var someCode = "blah-blah";/**comment*/';
    
      $minifiedJs = JSMin::minify($code);
    
      return $minifiedJs;
    }
    

    3 step: Don't forget to add use JSMin\JSMin; statement on top of your .php file.

    In your case, you will call it like removeComments($this->inlineScript()), if inlineScript() really returns string for you. As remark, normally inlineScript helper method should be called like this

    $jsCodeWithoutComments = removeComments($jsCodeWithComments);
    $this->inlineScript()->appendScript($jsCodeWithoutComments);
    

    See Append Javascript File to the end of the InlineScript Collection from child view

    That is it.