Wednesday, May 18th, 2022

How to async or defer JS to please Google

SEO gurus and website owners have been obsessed with Page Insights issues lately. While most of them refuse to understand how 100% optimization can affect the number of features they still want their sites to feature, they keep asking devs to fix them all.

When it comes to WordPress websites, especially those that use sophisticated plugins, running or running JS asynchronously can sometimes prevent snippets, blocks, or even entire pages from rendering properly. Huh.

Yes, we can still fix the dawn issues with Page Insights, but to get 100%, your customers need to make compromises. Having said that, it is possible (and really simple) to defer or async all JS scripts to the frontend.

never in backend

First and foremost, forget using this type of snippet for backend js dependencies. We don’t need a backend to meet Google’s whims 100%, and messing with admin dependencies can prevent a lot of tools and features from running.

Editors like Block Editor (WP current native editor), Elementor, WP Bakery, and a dozen others won’t work as you’d expect – and sometimes won’t even open. So, first of all, make sure you are blocking any changes to the frontend.

To manipulate script tags, we’ll need a function – inside it, all changes will be made inside a condition:

function async_enqueue($tag, $handle) {
    if(!is_admin()) {
    // Changes to script tags
    }
    return $tag;
}

As a general rule, you can now either defer or asynchronously load all attached JS into the frontend. To do this, all you have to do is add one of those lines inside the previous condition, and trigger the function using the correct filter.

// For deferring all JS
return str_replace( '<script ', '<script defer ', $tag );
// For loading all JS asynchronously
return str_replace( '<script ', '<script async ', $tag );

// After that, hook the function in the following filter
add_filter('script_loader_tag', 'async_enqueue', 10, 2);

a quick recollection

As mentioned earlier, some features of complex plugins may not work as expected when you defer or load JS in this way. If something goes wrong, add new conditions to your function to keep any JS files loaded as usual.

Source link