Kategorier
WordPress

Lazy load CSS in WordPress

When using Google PageSpeed Insights you might be presented for opportunities to speed up your application. Most likely, amongst those opportunities there will be a suggestion to:

Eliminate render-blocking resources

A solution to this is to lazy (or asynchronous) load your Style Sheets (CSS). This can be achieved by this piece of code in your themes functions.php file.

functions.php

/**
* dequeue stylesheets
* @return void
*/
function dequeue_styles() {
wp_dequeue_style('twentynineteen-print-style');
}
add_action('wp_enqueue_scripts', 'dequeue_styles', 20);

/**
* lazyload stylesheets
* @return void
*/
function lazyload_stylesheets() {
$uniqid = uniqid();
$styles = [
[
'rel' => 'stylesheet',
'href' => 'https://urlund.com/wp-content/themes/twentynineteen/print.css',
'type' => 'text/css',
'media' => 'print'
]
];

echo '
<script type="text/javascript">
    (function() {
        var ls'. $uniqid .' = '. json_encode($styles) .';
        ls'. $uniqid .'.forEach(function(attributes, index) {
            var link = document.createElement("link", attributes);
            for (var attribute in attributes) {
                link[attribute] = attributes[attribute];
            }

            document.getElementsByTagName("head")[0].appendChild(link);
        });
    })();
</script>
';
}
add_action('wp_footer', 'lazyload_stylesheets', 999);

Please note, you could dequeue further styles in the dequeue_styles function, and add them to the  $styles array (make sure to get the  media attribute right, eg. “all” instead of “print”).

Skriv et svar

Din e-mailadresse vil ikke blive publiceret. Krævede felter er markeret med *