Home / Comments / snip_FetchPriority
Duplicate Snippet

Embed Snippet on Your Site

snip_FetchPriority

FetchPriority pour LCP

Code Preview
php
<?php
add_action('template_redirect', function () {
    // On initialise un tableau global
    $GLOBALS['highfetchprio_preload'] = [];
    ob_start(function ($html) {
        // 1. On modifie les balises <img> ciblées
        $html = preg_replace_callback(
            '#<img([^>]+class="[^"]*highfetchprio[^"]*"[^>]*)>#i',
            function ($matches) {
                $img = $matches[0];
                // Supprimer lazyload et attributs inutiles
                $img = preg_replace('#\slazyload(ed)?#i', '', $img);
                $img = preg_replace('#\sdata-lazy-[a-z]+="[^"]*"#i', '', $img);
                // Supprimer anciens attributs
                $img = preg_replace('#\sfetchpriority="[^"]*"#i', '', $img);
                $img = preg_replace('#\sloading="[^"]*"#i', '', $img);
                $img = preg_replace('#\sdecoding="[^"]*"#i', '', $img);
                // Ajouter les bons attributs
                $img = str_replace('<img', '<img fetchpriority="high" loading="eager" decoding="async"', $img);
                // Stocker l'image pour preload (une seule fois par src)
                if (preg_match('#src="([^"]+)"#i', $img, $srcMatch)) {
                    $src = $srcMatch[1];
                    if (!in_array($src, $GLOBALS['highfetchprio_preload'], true)) {
                        $GLOBALS['highfetchprio_preload'][] = $src;
                    }
                }
                return $img;
            },
            $html
        );
        // 2. Injection du preload juste avant </head>
        if (!empty($GLOBALS['highfetchprio_preload'])) {
            $preloads = "";
            foreach ($GLOBALS['highfetchprio_preload'] as $src) {
                $preloads .= '<link rel="preload" as="image" href="' . esc_url($src) . '">' . "\n";
            }
            $html = preg_replace('#</head>#i', $preloads . '</head>', $html, 1);
        }
        return $html;
    });
});

Comments

Add a Comment