Kill WordPress Unused CSS and Compress HTML With Code Snippets

This code snippet is designed to optimize a WordPress site’s performance by compressing HTML output, removing unnecessary assets, and improving loading efficiency. It begins by compressing the HTML output, removing extra spaces and newlines to reduce the overall size of the HTML sent to the browser. This is achieved using the ob_start function, which starts output buffering and applies a series of regular expressions to the output buffer to minify the HTML. The shutdown action ensures that the buffer is properly flushed at the end of the request to send the optimized HTML to the browser.

The snippet also optimizes WordPress assets by removing unnecessary scripts and styles. It removes emoji-related scripts and styles, oEmbed scripts, and the jQuery Migrate script if it’s not needed on the frontend. Additionally, it conditionally dequeues the comment-reply script if comments are not open or threaded comments are not enabled.

Further optimizations include enabling lazy loading for images, which delays the loading of off-screen images until the user scrolls near them, thereby improving page load times. The code also removes the WordPress Block Library CSS from non-Gutenberg pages to avoid loading unnecessary styles. Finally, it deregisters the Dashicons stylesheet from the frontend for non-admin users to reduce the amount of CSS loaded.

The optimize_wp_assets function encapsulates these optimizations and is hooked into the wp_enqueue_scripts action with a high priority to ensure it runs after all other scripts and styles have been enqueued. This comprehensive approach helps improve the website’s performance by minimizing the amount of data sent to the user’s browser and reducing the load on the server.

// Compress HTML output and remove specific footer text
add_action('init', function() {
    ob_start(function($buffer) {
        $buffer = preg_replace('/\n\s+/', "\n", $buffer);
        $buffer = preg_replace('/>\s+</', '><', $buffer);
        $buffer = preg_replace('/\s+/', ' ', $buffer);
        return $buffer;
    });
});
// Ensure the buffer is flushed at the end of the request
add_action('shutdown', function() {
    if (ob_get_length()) {
        ob_end_flush();
    }
}, 999);
// Optimize WordPress assets
function optimize_wp_assets() {
    // Remove Emoji scripts and styles
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('wp_print_styles', 'print_emoji_styles');
    // Remove oEmbed scripts
    remove_action('wp_head', 'wp_oembed_add_host_js');
    // Dequeue jQuery Migrate if not needed
    add_filter('wp_default_scripts', function (&$scripts) {
        if (!is_admin()) {
            $scripts->remove('jquery');
            $scripts->add('jquery', false, array('jquery-core'), '1.12.4');
        }
    });
    // Dequeue comment-reply script if comments or threaded comments are not used
    add_action('wp_enqueue_scripts', function() {
        if (!is_singular() || !comments_open() || !get_option('thread_comments')) {
            wp_dequeue_script('comment-reply');
        }
    });	
	    // Lazy load images
    add_filter('wp_get_attachment_image_attributes', function($attr) {
        $attr['loading'] = 'lazy';
        return $attr;
    });
    // Remove WordPress Block Library CSS for non-Gutenberg pages
    add_action('wp_enqueue_scripts', function() {
        wp_dequeue_style('wp-block-library');
        wp_dequeue_style('wp-block-library-theme');
        wp_dequeue_style('global-styles'); // Since WordPress 5.9
    }, 100);
    // Remove Dashicons from the frontend for non-admin users
    add_action('wp_enqueue_scripts', function() {
        if (!current_user_can('update_core') && !is_admin_bar_showing()) {
            wp_deregister_style('dashicons');
        }
    });

}
// Hook the optimize_wp_assets function into wp_enqueue_scripts
add_action('wp_enqueue_scripts', 'optimize_wp_assets', 99);

Warning: All code found on this site is use at your own risk vibe. It worked for me when I wrote it, but if it breaks your stuff don’t come shout at me. Happy to help if I can, but there are no guarantees expressed and implied. This is merely an example for developers most of the code examples on this site are scripts that are used in Code Snippets functions.

Removing unnecessary scripts and styles can significantly improve Google Page Speed scores by reducing the amount of data that needs to be transferred from the server to the client, minimizing render-blocking resources, and decreasing the overall time it takes for a page to load. Here’s a detailed explanation:

  1. Reduced Data Transfer:
    • Unnecessary scripts and styles increase the amount of data that must be downloaded by the browser. By removing these, the browser has fewer resources to download, resulting in faster page load times.
  2. Minimized Render-Blocking Resources:
    • Scripts and styles, especially those in the head of an HTML document, are render-blocking, meaning they must be downloaded, parsed, and executed before the page can be rendered. Removing unnecessary resources allows the browser to render the page more quickly.
  3. Improved First Contentful Paint (FCP):
    • The FCP metric measures the time it takes for the first piece of content to be rendered on the screen. By reducing the number of scripts and styles, the FCP is improved as the browser can display content sooner.
  4. Enhanced Time to Interactive (TTI):
    • TTI measures how long it takes for a page to become fully interactive. By removing unnecessary scripts, the main thread is less congested, enabling the page to become interactive more quickly.
  5. Lower Total Blocking Time (TBT):
    • TBT is the total time between FCP and TTI that the main thread was blocked. Fewer scripts result in less blocking time, contributing to better TBT scores.

Gutenberg

Oh, WordPress, how you’ve betrayed your loyal users with the monstrosity known as Gutenberg! What were you thinking, foisting this clunky, bloated editor upon us? It’s as if you’ve taken a beautifully simple, streamlined system and turned it into a labyrinthine mess. Gutenberg is the epitome of unnecessary bloat, packed with scripts and styles that drag our websites into the depths of sluggish performance.

Gutenberg’s block-based approach, while perhaps innovative in theory, is a disaster in execution. Each block is a cesspool of excess code, contributing to longer load times and horrific Google Page Speed scores. The sheer volume of CSS and JavaScript files that Gutenberg loads is enough to make any site crawl at a snail’s pace. And let’s not even get started on the render-blocking resources that keep our users staring at blank screens longer than ever before.

It’s almost as if WordPress has forgotten its roots. Where is the simplicity? The efficiency? Gutenberg has transformed WordPress into a hulking behemoth that devours bandwidth and spits out slow, unresponsive pages. We, the users, are left to pick up the pieces, desperately trying to optimize and strip away the unnecessary bloat that Gutenberg imposes upon us.

In the quest for modernity and flexibility, WordPress has sacrificed speed and user experience on the altar of Gutenberg. It’s high time we return to the basics, to an era where WordPress was synonymous with simplicity and speed, not the slow, cumbersome beast it has become. Down with Gutenberg and its gluttonous appetite for resources!

The pollution wrought by Gutenberg has now insidiously spread to WooCommerce, compounding the agony for the WordPress community. It’s bad enough that Gutenberg’s bloat and inefficiency have infected our beloved content editor, but now, this malignancy has been forced upon WooCommerce, a vital lifeline for countless online businesses. The sheer audacity of force-feeding this garbage to the WordPress community will not go unpunished. Merchants and developers alike are grappling with the performance degradation and inflated load times caused by this unnecessary bulk, leading to lost sales and frustrated users. WooCommerce, once a beacon of e-commerce simplicity and power, is now shackled with the burdensome weight of Gutenberg’s bloated code. The community’s outcry grows louder with each sluggish page load, demanding a return to efficiency and the eradication of this invasive menace from our vital tools. The betrayal is palpable, and the resolve to fight back against this enforced monstrosity is unwavering.

"Software is like sex: it's better when it's free."

Linus Torvalds

Leave a Reply

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

Scroll to top