A+ A-

Async with WordPress Enqueue

If you regularly build sites with WordPress and test them against Google PageSpeed Insights, you’ll probably have encountered it complaining about async and defer on your scripts.

So, you’d normally simply add ‘async’ to your script tag, but if you’re enqueuing your scripts correctly via your WordPress functions.php file, you’ll no doubt have realised that there is no parameter to add async when using the WordPress wp_enqueue_script() function.

This is a relatively easy fix.


How do we do it?

First off, you’re going to want to open your functions.php file in your favourite text editor, then we’re going to create our async function.

Notice also, we have prefixed our function name to prevent any conflicts with plugins or other functions.

// Async load
function ikreativ_async_scripts($url)
{
    if ( strpos( $url, '#asyncload') === false )
        return $url;
    else if ( is_admin() )
        return str_replace( '#asyncload', '', $url );
    else
	return str_replace( '#asyncload', '', $url )."' async='async"; 
    }
add_filter( 'clean_url', 'ikreativ_async_scripts', 11, 1 );

This function is simply looking for the #asyncload string, and, if found, appending async='async' to the URL.

Now you can enqueue your scripts as normal, and simply add the #asyncload string to any script you want to async.

// Enqueue scripts
function ikreativ_theme_scripts()
{
    // wp_enqueue_script() syntax, $handle, $src, $deps, $version, $in_footer(boolean)
    wp_enqueue_script( 'plugins', get_template_directory_uri() . '/assets/js/plugins.min.js#asyncload', 'jquery', '', true );
    wp_enqueue_script( 'application', get_template_directory_uri() . '/assets/js/application.min.js#asyncload', 'jquery', '', true );
}
add_action( 'wp_enqueue_scripts', 'ikreativ_theme_scripts');

Conclusion.

So there you have it, a simple fix to correctly enqueue WordPress scripts with async in order conform with Google PageSpeed Insights.

About Scott

Freelance Web Designer. Developer. SEO Consultant. WordPress Evangelist. Theme Creator. Reviewer @Envato. Founder iKreativ, LoveThemes, NakedApes & Creator of Workless

Join the Discussion.

Outdoor Apparel