Skip to content

Instantly share code, notes, and snippets.

@zmsaunders
Last active August 7, 2022 10:54
Show Gist options
  • Select an option

  • Save zmsaunders/5619519 to your computer and use it in GitHub Desktop.

Select an option

Save zmsaunders/5619519 to your computer and use it in GitHub Desktop.
HTML Output Minification in laravel 4
<?php
### --- Snip --- ###
App::after(function($request, $response)
{
// HTML Minification
if(App::Environment() != 'local')
{
if($response instanceof Illuminate\Http\Response)
{
$output = $response->getOriginalContent();
// Clean comments
$output = preg_replace('/<!--([^\[|(<!)].*)/', '', $output);
$output = preg_replace('/(?<!\S)\/\/\s*[^\r\n]*/', '', $output);
// Clean Whitespace
$output = preg_replace('/\s{2,}/', '', $output);
$output = preg_replace('/(\r?\n)/', '', $output);
$response->setContent($output);
}
}
});
### --- Snip --- ###
@ajmcagadas

Copy link
Copy Markdown

Thanks @zach && @garagesocial, I added a substitute for HTML comment filter to exclude the IE conditions. https://gist.github.com/paparts/9113258

@viniciusmr3

Copy link
Copy Markdown

Well done @zmsaunders! It helped a lot! Cheers!

@miguelbalboa

Copy link
Copy Markdown

Verify that the response header is text/html, to avoid problems when returning an image for example.
https://gist.github.com/miguelbalboa/9224ecc1daeadff5ab49

@morilog

morilog commented Dec 9, 2014

Copy link
Copy Markdown

minifying only text/html output

// HTML Minification
    if(App::Environment() != 'local')
    {
        if($response instanceof Illuminate\Http\Response)
        {
            $output = $response->getOriginalContent();
            if($response->headers->get('content-type') == 'text/html; charset=UTF-8')
            {
                // Clean comments
                $output = preg_replace('/<!--([^\[|(<!)].*)/', '', $output);
                $output = preg_replace('/(?<!\S)\/\/\s*[^\r\n]*/', '', $output);
                // Clean Whitespace
                $output = preg_replace('/\s{2,}/', '', $output);
                $output = preg_replace('/(\r?\n)/', '', $output);
                $response->setContent($output);
            }
        }
    }

@rafelsanso

Copy link
Copy Markdown

This code has an important error. Run the full content of the page twice. The first to generate the page, and the second to go through the :: after. That doubles the load times. I think it's worse than spending the HTML uncompressed. You can do the test by putting a log on a page and see that the refresh the log is printed twice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment