Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
Wordpress

WordPress Speed Hack: How Lazy Loading Images Cuts Page Load Time in Half

- 05.02.26 - ErcanOPAK

WordPress sites loading slowly due to images? Native lazy loading with modern techniques dramatically improves performance.

// Add to functions.php
function add_lazy_loading_attributes($content) {
    // Only run on frontend
    if (is_admin() || wp_is_json_request()) {
        return $content;
    }
    
    // Use DOMDocument for reliable parsing
    if (class_exists('DOMDocument')) {
        $dom = new DOMDocument();
        @$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
        
        $images = $dom->getElementsByTagName('img');
        
        foreach ($images as $image) {
            // Skip if already has loading attribute
            if ($image->hasAttribute('loading')) {
                continue;
            }
            
            // Add loading='lazy' to all images
            $image->setAttribute('loading', 'lazy');
            
            // Add decoding='async' for better performance
            $image->setAttribute('decoding', 'async');
            
            // If image is above the fold (first 3 images), use eager
            static $image_count = 0;
            if ($image_count < 3) {
                $image->setAttribute('loading', 'eager');
                $image_count++;
            }
        }
        
        // Save the modified HTML
        $content = $dom->saveHTML();
    }
    
    return $content;
}
add_filter('the_content', 'add_lazy_loading_attributes', 99);
add_filter('post_thumbnail_html', 'add_lazy_loading_attributes', 99);
add_filter('get_avatar', 'add_lazy_loading_attributes', 99);
add_filter('woocommerce_product_get_image', 'add_lazy_loading_attributes', 99);

// Advanced: Native lazy loading with intersection observer fallback
function enqueue_lazy_loading_scripts() {
    // Only for browsers that don't support native lazy loading
    wp_add_inline_script('jquery', '
        document.addEventListener("DOMContentLoaded", function() {
            if ("loading" in HTMLImageElement.prototype) {
                // Browser supports native lazy loading
                console.log("Using native lazy loading");
            } else {
                // Fallback to intersection observer
                console.log("Using intersection observer fallback");
                
                const images = document.querySelectorAll("img[loading=\"lazy\"]");
                
                if ("IntersectionObserver" in window) {
                    const imageObserver = new IntersectionObserver((entries) => {
                        entries.forEach((entry) => {
                            if (entry.isIntersecting) {
                                const img = entry.target;
                                img.src = img.dataset.src;
                                if (img.dataset.srcset) {
                                    img.srcset = img.dataset.srcset;
                                }
                                imageObserver.unobserve(img);
                            }
                        });
                    });
                    
                    images.forEach((img) => {
                        // Store original src in data-src
                        img.dataset.src = img.src;
                        img.dataset.srcset = img.srcset || "";
                        img.src = "data:image/svg+xml,%3Csvg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 1 1\"%3E%3C/svg%3E";
                        img.srcset = "";
                        imageObserver.observe(img);
                    });
                } else {
                    // Fallback for very old browsers
                    images.forEach((img) => {
                        img.src = img.dataset.src;
                        if (img.dataset.srcset) {
                            img.srcset = img.dataset.srcset;
                        }
                    });
                }
            }
        });
    ');
}
add_action('wp_enqueue_scripts', 'enqueue_lazy_loading_scripts');

Related posts:

Stop WordPress from Killing Your Site During Plugin Updates

Stop WordPress from Killing Your Site During Plugin Updates

WordPress Search Is Slow Even on Small Sites

WordPress Search Is Slow Even on Small Sites

WordPress: Fix a Multisite Subsite's Uploads Pointing to the Wrong Domain Because the Site URL Was C...

WordPress: Fix a Multisite Subsite's Uploads Pointing to the Wrong Domain Because the Site URL Was C...

Views: 12

Post navigation

Git Hooks Automation: Pre-commit Checks That Save Hours of Debugging
Windows 11 WSL2: Run Linux at Native Speed Without Dual Boot

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (482)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com