WordPress How To Load Javascript Files Asynchronously Without A Plugin
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