logo

Pablo Guides

In WordPress, you can defer loading images, JavaScript (JS), and Cascading Style Sheets (CSS) using custom functions. Deferment involves delaying the loading of certain assets until after the initial page load. Below is an example code snippet that you can use in your theme's functions.php file.

1. Defer JavaScript:

function defer_javascript($url) {
    if (is_user_logged_in()) {
        return $url; // Don't defer for logged-in users
    }
    
    if (strpos($url, '.js') === false) {
        return $url; // Do not defer non-JS files
    }

    return "$url' defer='defer";
}
add_filter('clean_url', 'defer_javascript', 11, 1);

This function hooks into the clean_url filter and appends the defer attribute to JavaScript files. It checks if the user is logged in, and if so, it doesn't defer the JavaScript to avoid potential issues with the WordPress admin area.

2. Defer CSS:

function defer_css($content) {
    if (is_user_logged_in()) {
        return $content; // Don't defer for logged-in users
    }

    $content = str_replace('stylesheet', 'stylesheet" defer="defer', $content);
    return $content;
}
add_filter('style_loader_tag', 'defer_css');

This function hooks into the style_loader_tag filter and appends the defer attribute to CSS files. Similar to the JavaScript function, it checks if the user is logged in and avoids deferring styles for logged-in users.

3. Defer Images:

For deferring images, it's a bit more complex as it typically involves using JavaScript. You can enqueue a custom script to handle image deferral.

function enqueue_defer_images_script() {
    wp_enqueue_script('defer-images', get_template_directory_uri() . '/js/defer-images.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_defer_images_script');

Create a defer-images.js file in your theme's js directory with the following content:

document.addEventListener('DOMContentLoaded', function() {
    var images = document.querySelectorAll('img[data-src]');
    images.forEach(function(img) {
        img.setAttribute('src', img.getAttribute('data-src'));
    });
});

This script defers loading of images by setting the src attribute from data-src when the DOM has fully loaded.

Remember to customize these code snippets according to your specific needs and test thoroughly to ensure compatibility with your theme and plugins. Additionally, consider the impact on your site's performance and user experience before implementing such changes.

Pablo Guides