Scotts Web Dev Banner
Did you notice... every article on this site has an associated video? Consider subscribing to Scotts Web Dev on YouTube! :)

Defer WordPress Javascript Files For Better PageSpeed

PageSpeed Will Complain About Javascript Blocking The Page

You’ll see lots of errors about javascript files in lighthouse pagespeed. It will complain about them being blocking. The solution to this is to only load the necessary scripts at first and load all of the other scripts when the page mostly finishes loading and loading the scripts with a defer attribute.

With the defer attribute set, the script is downloaded, but it is not executed until after the page has finished loading.

Also, Load Non-Essential Scripts In The Footer

There’s a parameter to wp_enqueue_script to load the script in the footer. I’ve found that this increases the pagespeed when combined with the defer attribute.

Defer Scripts Code Snippet

/**
* Scottsweb.dev
* https://scottsweb.dev/defer-wordpress-scripts-pagespeed/
* defer scripts so they are non blocking
*/
function swd_do_defer($tag, $handle) {
  // an array of script id's to defer here
	$do_defer = array('big-picture', 'slick-slider');

  // if the id is in the array, defer it
	if (in_array($handle, $do_defer)) {
		return str_replace(' src', ' defer src', $tag);
	}

  // otherwise, return the tag
	return $tag;
}

// add the filter and run swd_do_defer callback function
add_filter('script_loader_tag', 'swd_do_defer', 10, 2);

Explaining The Defer Script

Place this code in your functions.php, or your child themes functions.php, or another globally included file.

What we are doing here is adding a filter to the script_loader_tag. This callback function defines an array of script id’s inside the function. So you’ll need to hardcode these id’s in this array.

Then it checks if the id is in the array for the tag passed in, and if it is, adds a defer attribute to the script tag.

You can find the script id of your javascript files by viewing the source and looking for <script id=”xxx-js”>, where xxx-js is the name of your script.

Remember to remove the -js in the script id when adding it to the array.

See more wordpress pagespeed tips and tricks.