The Problem: Render-blocking JavaScript
When a web browser loads your WordPress site, it reads your code from top to bottom.
If it runs into a JavaScript file, it pauses everything else to download and run that script first.
This causes a delay in your page loading speed, hurting your user experience and dropping your mobile performance scores.
By adding a defer attribute to these scripts, you tell the browser to keep downloading the visual parts of your webpage first.
And loading the heavy scripts only after the page is fully displayed.
How to defer JavaScript in WordPress using functions.php
Follow these steps to apply a site-wide script deferral filter while safely leaving core libraries like jQuery untouched to prevent plugin breakages.
Step 1: Open your theme's functions.php file
- Log in to your WordPress Dashboard.
- Navigate to Appearance and select Theme File Editor.
- Locate and click on functions.php (Theme Functions) from the file list on the right side.
Step 2: Add the optimization code
Scroll down to the absolute bottom of the file and paste the following code snippet:
// Do not defer core jQuery to prevent site features from breaking
if ( 'jquery-core' === $handle ) {
return $tag;
}
return str_replace( ' src', ' defer="defer" src', $tag );
}
add_filter( 'script_loader_tag', 'defer_non_essential_js', 10, 3 );
Step 3: Save and test your site
- Click the Update File button below the code editor.
- Head over to Google PageSpeed Insights and run your URL audit again to verify that your render-blocking warnings have decreased.
functions.php file handles core site mechanics and is highly sensitive. Even a small missing semicolon can cause a temporary critical error on your site. For absolute safety, it is highly recommended to add custom code blocks using a child theme or a dedicated code management plugin like Code Snippets.
RELATED PERFORMANCE TIPS:
