Home / Disable / Site-Wide Hero Optimisation
Duplicate Snippet

Embed Snippet on Your Site

Site-Wide Hero Optimisation

Scott Cassidy
<10
Code Preview
php
<?php
/**
 * Promote the hero image (LCP) site-wide:
 * - fetchpriority="high", loading="eager"
 * - remove lazy markers from LiteSpeed/Smush
 * - inject <link rel="preload" as="image"> in <head>
 * Works on every page using the shared hero structure.
 */
add_action( 'wp_head', function () { ?>
<script>
(function () {
  // Update this list if your hero selector ever changes
  var selectors = [
    '.background-image-wrapper .background-image img',
    '.hero-header img',
    '.entry-header img'
  ];
  function findHero() {
    for (var i = 0; i < selectors.length; i++) {
      var img = document.querySelector(selectors[i]);
      if (img) return img;
    }
    return null;
  }
  function deLazy(img) {
    // Stop lazy systems
    ['lazy', 'lazyload', 'lazyloaded', 'litespeed-loaded', 'entered', 'skipped-lazy']
      .forEach(function (c) { img.classList.remove(c); });
    ['data-src','data-srcset','data-lazy-src','data-lazyload','data-ll-status','data-lazyloaded']
      .forEach(function (a) { img.removeAttribute(a); });
    // If any lazy plugin kept the URL in data-src, use it
    if (!img.src) {
      var ds = img.getAttribute('data-src') || img.getAttribute('data-lazy-src');
      if (ds) img.src = ds;
    }
  }
  function promote(img) {
    try {
      deLazy(img);
      // Correct attributes for LCP
      img.setAttribute('loading', 'eager');
      img.setAttribute('fetchpriority', 'high');
      if (!img.hasAttribute('sizes')) img.setAttribute('sizes', '100vw');
      // Preload in head (no duplicates)
      var href = img.currentSrc || img.src;
      if (href && !document.querySelector('link[rel="preload"][as="image"][href="' + href + '"]')) {
        var link = document.createElement('link');
        link.rel = 'preload';
        link.as = 'image';
        link.href = href;
        link.fetchPriority = 'high';
        document.head.appendChild(link);
      }
    } catch (e) {}
  }
  function run() {
    var img = findHero();
    if (img) promote(img);
  }
  // Run ASAP
  if (document.readyState !== 'loading') { run(); }
  else { document.addEventListener('DOMContentLoaded', run, { once: true }); }
})();
</script>
<?php
}, 1);

Comments

Add a Comment