May 7, 2015

Textual description of firstImageUrl

How to Problemfix eliminate render-blocking JavaScript in WordPress

|
If Google PageSpeed Insights warns you to eliminate render-blocking resources on your WordPress site, deferring non-essential JavaScript is one of the fastest fixes. Adding a small, optimized function to your theme lets you delay script execution so your main page content loads instantly.

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.

Eliminate Render-Blocking JavaScript in WordPress

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

  1. Log in to your WordPress Dashboard.
  2. Navigate to Appearance and select Theme File Editor.
  3. 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:

function defer_non_essential_js( $tag, $handle, $src ) {
    // 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

  1. Click the Update File button below the code editor.
  2. Head over to Google PageSpeed Insights and run your URL audit again to verify that your render-blocking warnings have decreased.

⚠️ Crucial Safety Note: The 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: