WordPress How To Load Javascript Files Asynchronously Without A Plugin


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







WordPress How To Load Javascript Files Asynchronously Without A Plugin

Over the last few days, I’ve written a couple articles on how to improve your Google Page Speed Insights test. These posts included:

 
Today, I’m going to take a look at how to load javascript files asynchronously and improve upon the “Eliminate render-blocking JavaScript and CSS in above-the-fold content” line item that is often seen in the Page Insights Test.

To start, we’re going to open up our functions.php file and insert the following lines of code:

 

function add_async_forscript($url) {
    if (strpos($url, '#wpcasync')===false)
        return $url;
    else if (is_admin())
        return str_replace('#wpcasync', '', $url);
    else
        return str_replace('#wpcasync', '', $url)."' async='async"; 
}
add_filter('clean_url', 'add_async_forscript', 11, 1);

 

What this function is going to do is add the async=’async’ attribute to any javascript file that has #wpcasync appended to the end of the file. As an example, my current JS script loaded in my functions.php file might look something like this:
 

wp_enqueue_script( 'my-js-script', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), '2.1', true );

 
To load this script asynchronously, I would append #wpcasync to the end of the file like so:
 

wp_enqueue_script( 'my-js-script', get_template_directory_uri() . '/js/script.js#wpcasync', array( 'jquery' ), '2.1', true );

 
This script will now be prompted to load asynchronously rather than cause render blocking prior to the script loading. Note that you need to be well versed in javascript to add the #wpcasync addon to your script URLs. This cannot be added to every javascript file you call as it will likely break your site. Some files will need to be loaded prior to rendering the content.


Share Your Thoughts

Leave a Reply

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


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!