javascript - 缩小内联脚本

标签 javascript php zend-framework2 minify view-helpers

在我的 View 脚本中,我使用 View 助手添加 javascript inlineScript并在我的模板的页脚中回应它。我现在正尝试使用 this solution 缩小生成的 html .

我的问题是我在整个代码中包含内联注释(例如 //this is a comment)(因为我是一个优秀的开发人员),这导致所有代码都被视为注释很好(因为所有新行都被删除,并且以下代码与内联注释放在同一行)。

如何扩展 inlineScript 以删除注释和/或使用例如 mrclay minify 缩小代码?

我试过的是:

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

这会导致我有代码的页面出现问题,例如:

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(''))

并且,上述的变体,

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

它检查之前没有任何内容的评论。这引发了我在代码后跟行末注释的问题:

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

这会产生与原始问题相同的不良结果。

最佳答案

您可以添加 https://github.com/mrclay/jsmin-php删除评论和空格(请参阅问题 https://github.com/mrclay/minify/issues/581 关于评论)。

如果您正在使用 composer 项目,您可以通过以下方式将 jsmin-php 添加到您的项目中:

第一步:composer.json 所在的终端中运行 composer require mrclay/jsmin-php 以安装包。

2 步:将带有 JSMin::minify 的行添加到您的脚本缩小功能的实现中,这将删除评论:

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 步:不要忘记在 .php 文件顶部添加 use JSMin\JSMin; 语句。

在您的情况下,如果 inlineScript() 真的为您返回字符串,您将像 removeComments($this->inlineScript()) 那样调用它。需要注意的是,通常 inlineScript 辅助方法应该这样调用

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

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

就是这样。

关于javascript - 缩小内联脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50507016/

相关文章:

javascript - 使用Sinon.JS和Rewire时是否可以设置 `this`的值?

php - 为什么我的变量通过引用传递?

php - 如何从 LAST_INSERT_ID (`my_column` +1) 获取表达式的值?

php - TinyMCE 不在编辑器中显示格式化文本

javascript - 替换后动画至高度 0

javascript - react native 列表空组件在部分列表中不起作用

javascript - 如何修复错误 : object is not valid as React child

php - Amazon RDS 和 Zend Framework 2

php - Zend Framework 2 中的服务定位器

php - Zend\Db 是否有任何 MySQL 版本限制?