Yusuf

Navigation

Minify HTML in Laravel

Minify HTML in Laravel: Optimize Your Application’s Output

In web development, performance matters, and every millisecond saved counts. If you’ve used JavaScript frameworks with server-side rendering (SSR), you may have noticed that HTML is often compressed when built. Laravel doesn’t do this by default, but with some simple steps, you can achieve this in your Laravel applications. In this article, we’ll walk through how to set up HTML minification in Laravel to improve performance by reducing page size.


What is HTML Minification?

HTML minification is the process of removing unnecessary characters like spaces, tabs, and newlines from your HTML without affecting how browsers render the content. By doing this, you can reduce the size of the HTML response and ultimately improve load times.

Let’s explore how to implement this in Laravel.


Step 1: Creating the HTML Minifier Helper Class

Let’s create a helper class to handle the minification process in Laravel. This class will clean up your HTML content by removing whitespace, comments, and other unnecessary characters.

<?php

namespace App\Support;

class HtmlMinifier
{
    const EXCLUDESTART = '<!-- EXCLUDE_MINIFY_START -->';
    const EXCLUDEEND = '<!-- EXCLUDE_MINIFY_END -->';

    public static function minify(string $html): string
    {
        $replace = [
            '/\>[^\S ]+/s' => '>', // Remove spaces after tags
            '/[^\S ]+\</s' => '<', // Remove spaces before tags
            '/([\t ])+/s' => ' ',  // Shorten multiple spaces
            '/^([\t ])+/m' => '',  // Remove leading spaces
            '/([\t ])+$/m' => '',  // Remove trailing spaces
            '/~//[a-zA-Z0-9 ]+$~m/' => '', // Remove JS line comments
            '/\>[\r\n\t ]+\</s' => '><',  // Remove empty lines
            '/}[\r\n\t ]+/s' => '}',     // Remove line breaks after JS blocks
            '/\)[\r\n\t ]?{[\r\n\t ]+/s' => '){', // Remove line breaks after JS functions
        ];

        // Exclude sections marked with special tags
        preg_match_all('/' . self::EXCLUDESTART . '(.*?)' . self::EXCLUDEEND . '/s', $html, $matches);
        foreach ($matches[0] as $index => $exclude) {
            $html = str_replace($exclude, "%%%EXCLUDE_$index%%%", $html);
        }

        $html = preg_replace(array_keys($replace), array_values($replace), (string) $html);

        foreach ($matches[0] as $index => $exclude) {
            $html = str_replace("%%%EXCLUDE_$index%%%", $exclude, $html);
        }

        return $html;
    }
}

This HtmlMinifier class efficiently removes unnecessary whitespace and comments, ensuring your HTML remains functional but significantly smaller in size.


Step 2: Creating Middleware to Apply Minification

To automatically minify HTML responses, we’ll create a middleware. This middleware will check if the response can be minified and then use the HtmlMinifier class to process the HTML.

<?php

namespace App\Http\Middleware;

use App\Support\HtmlMinifier;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class Minify
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        if ($this->canMinify($response)) {
            $response->setContent(HtmlMinifier::minify($response->getContent()));
        }

        return $response;
    }

    protected function canMinify($response): bool
    {
        return is_object($response) && $response instanceof Response && $response->isSuccessful();
    }
}

This middleware checks if the response is successful and, if so, applies HTML minification. You can register this middleware in Kernel.php to apply it globally or to specific routes.


Step 3: Comparing Unminified and Minified Output

Here’s the unminified HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>My Laravel App</title>
    </head>
    <body>
        <h1>Welcome to My Laravel Application</h1>
        <p>This is an example of an unminified HTML output.</p>
    </body>
</html>

After applying the minifier, the output looks like this:

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>My Laravel App</title></head><body><h1>Welcome to My Laravel Application</h1><p>This is an example of a minified HTML output.</p></body></html>

The unnecessary spaces and line breaks are gone, reducing the overall size of the HTML document.


Conclusion

Minifying HTML can make a notable difference in your application’s performance by reducing the size of the content sent to the browser. While it’s not enabled by default in Laravel, creating a simple helper class and middleware allows you to implement HTML minification in no time. With this setup, your Laravel application will serve faster, more efficient HTML.


Source