简体   繁体   中英

Minify HTML code without breaking inline Javascript

I have been caching rendered pages to a redis cache and serving them to non logged in users as a speedy cache. The page size for most pages is hitting around 100kb. I was able to knock 20kb off the size by minifying the html before inserting it into redis, but it seems that this process breaks any inline javascript on the pages.

Am using the following PHP function to perform the minify at the moment. I have had to disable it of course, but it seems to be doing OK, just needs to be more weary of javascript.

function MinifyHtml($html)
{
    $search = array(
        '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
        '/[^\S ]+\</s',     // strip whitespaces before tags, except space
        '/(\s)+/s',         // shorten multiple whitespace sequences
        '/<!--(.|\s)*?-->/' // Remove HTML comments
    );

    $replace = array('>','<','\\1','');

    $buffer = preg_replace($search, $replace, $html);

    return $buffer;
}

我已经使用PHP函数缩小HTML和JavaScript的范围,可以在这里找到: https : //gist.github.com/tovic/d7b310dea3b33e4732c0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM