Skip to content

Instantly share code, notes, and snippets.

@khoipro
Created March 5, 2026 10:28
Show Gist options
  • Select an option

  • Save khoipro/2dac901d08b00f018b0a1896f272c29b to your computer and use it in GitHub Desktop.

Select an option

Save khoipro/2dac901d08b00f018b0a1896f272c29b to your computer and use it in GitHub Desktop.
Optimize content: first image no lazyload
<?php
$counter = 0;
$content = preg_replace_callback(
'/<img([^>]+)>/i',
function ($matches) use (&$counter) {
$counter++;
$imgTag = $matches[0];
// Remove any existing loading attribute
$imgTag = preg_replace('/\sloading=["\']?\w+["\']?/i', '', $imgTag);
if ($counter === 1) {
// First image: add fetchpriority and no-lazy class
if (preg_match('/class=["\']([^"\']*)["\']/', $imgTag, $classMatch)) {
$newClass = trim($classMatch[1] . ' no-lazy');
$imgTag = preg_replace('/class=["\'][^"\']*["\']/', 'class="' . $newClass . '"', $imgTag);
} else {
$imgTag = str_replace('<img', '<img class="no-lazy"', $imgTag);
}
$imgTag = str_replace('<img', '<img fetchpriority="high"', $imgTag);
} else {
// Subsequent images: lazysizes style
// Replace src with data-src
$imgTag = preg_replace('/src=(["\'])(.*?)\1/i', 'data-src=$1$2$1', $imgTag);
if (preg_match('/class=["\']([^"\']*)["\']/', $imgTag, $classMatch)) {
$newClass = trim($classMatch[1] . ' lazyload');
$imgTag = preg_replace('/class=["\'][^"\']*["\']/', 'class="' . $newClass . '"', $imgTag);
} else {
$imgTag = str_replace('<img', '<img class="lazyload"', $imgTag);
}
}
return $imgTag;
},
$content
);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment