JosephSilber / page-cache

Caches responses as static files on disk for lightning fast page loads.
MIT License
1.21k stars 118 forks source link

Minify Html Maybe make it Optional #95

Closed JagsGill123 closed 2 years ago

JagsGill123 commented 2 years ago

it would be nice to have an option to minify the html files. I noticed I was able to reduce file size from 30kb to 15kb using the below

for even faster load times.

I grabbed the below minify code from stackoverflow else but maybe there is better

/**
     * Cache the response to a file.
     *
     * @param  \Symfony\Component\HttpFoundation\Request  $request
     * @param  \Symfony\Component\HttpFoundation\Response  $response
     * @return void
     */
    public function cache(Request $request, Response $response)
    {
        list($path, $file) = $this->getDirectoryAndFileNames($request, $response);

        $this->files->makeDirectory($path, 0775, true, true);

        $this->files->put(
            $this->join([$path, $file]),
            $this->minifyHtml($response->getContent()),
            true
        );
    }

    /**
     * Minify html can save half a file size
     *
     * @param $html
     * @return string|string[]|null
     */
    private function minifyHtml($html)
    {
        $search = array(
            '/(\n|^)(\x20+|\t)/',
            '/(\n|^)\/\/(.*?)(\n|$)/',
            '/\n/',
            '/\<\!--.*?-->/',
            '/(\x20+|\t)/', # Delete multispace (Without \n)
            '/\>\s+\</', # strip whitespaces between tags
            '/(\"|\')\s+\>/', # strip whitespaces between quotation ("') and end tags
            '/=\s+(\"|\')/'); # strip whitespaces between = "'

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

        $html = preg_replace($search,$replace,$html);
        return $html;
    }
JosephSilber commented 2 years ago

Minification is out of scope for this package. You can easily add it as its own middleware in your app.