Home / Archive / Safe Performance Middleware for NexSouk.com
Duplicate Snippet

Embed Snippet on Your Site

Safe Performance Middleware for NexSouk.com

Safe Performance Middleware for NexSouk.com

Code Preview
php
<?php
<?php
// Safe Performance Middleware for NexSouk.com
ob_start(function ($buffer) {
    // 1. Preload critical font only if head exists (non-breaking)
    $buffer = preg_replace(
        '/<head>/i',
        "<head>\n" .
        "<link rel='preload' href='/assets/fonts/your-font.woff2' as='font' type='font/woff2' crossorigin>\n",
        $buffer
    );
    // 2. Ensure font-display: swap (optional: only if it's present)
    $buffer = str_replace("font-display: optional;", "font-display: swap;", $buffer);
    // 3. Add lazy-loading to <img> tags (only if loading attribute is missing)
    $buffer = preg_replace_callback('/<img\s+[^>]*>/i', function ($match) {
        $imgTag = $match[0];
        if (stripos($imgTag, 'loading=') === false) {
            return preg_replace('/<img/i', '<img loading="lazy"', $imgTag);
        }
        return $imgTag;
    }, $buffer);
    // 4. Safe WebP enhancement – only if WebP file exists
    $buffer = preg_replace_callback('/<img\s[^>]*src="([^"]+\.(jpg|jpeg|png))"[^>]*>/i', function ($matches) {
        $originalTag = $matches[0];
        $src = $matches[1];
        $webp = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $src);
        $webpPath = $_SERVER['DOCUMENT_ROOT'] . $webp;
        if (file_exists($webpPath)) {
            return "<picture>
                <source srcset=\"$webp\" type=\"image/webp\">
                $originalTag
            </picture>";
        }
        return $originalTag; // Leave original if WebP not available
    }, $buffer);
    return $buffer;
});
// 5. Set safe, long cache headers (non-invasive, helps efficiency)
if (!headers_sent()) {
    header("Cache-Control: public, max-age=31536000, immutable");
    header("Vary: Accept-Encoding");
}
?>

Comments

Add a Comment