Use code PERFMATTERS for an extra 10% off!
  1. Home
  2. Docs
  3. General
  4. How to delay JavaScript until user interaction in WordPress

How to delay JavaScript until user interaction in WordPress

While defer JavaScript pushes the script to the bottom of the page load, you can instead delay JavaScript based on user interaction. This can be a great way to speed up the paint of the page for Google Lighthouse when something isn’t needed right away. Especially heavy third-party scripts like Google Adsense, Google Analytics, conversion pixels (FB, Google Ads), etc.

It also works great for things like cart fragments which is a common WooCommerce performance issue due to the fact that the AJAX request can’t be cached. You can also use it with our local analytics feature and Instant Page.

Delay JavaScript

Follow the steps below to delay JavaScript with Perfmatters. This should work with a script tag with either the type='javascript' or no type.

Step 1

Click into the Perfmatters plugin settings.

Perfmatters plugin settings
Perfmatters plugin settings

Step 2

Under the “Options” tab, click on the “Assets” sub-navigation menu.

Perfmatters Assets
Perfmatters Assets

Step 3

Scroll down and under the “JavaScript” section, toggle on “Delay JavaScript.”

Delay JavaScript
Delay JavaScript

Step 4

Then proceed to choose your Delay behavior.

Delay behavior

There are two different methods you can choose from to delay JavaScript:

  1. Only delay specificed scripts
  2. Delay all scripts (BETA)
Perfmatters JavaScript delay behavior
Perfmatters JavaScript delay behavior

1. Only delay specified scripts

Delay specific JavaScript files by adding the source URL (example.js), or delay an inline script by adding a unique string from that script. Format: one per line

Delay specified JavaScript with Perfmatters
Delay specified JavaScript with Perfmatters

2. Delay all scripts (BETA)

The delay all scripts feature will attempt to delay all JavaScript, including inline. This is by far the most aggressive option. Note: This feature is in BETA. You can then exclude scripts if needed.

Excluded from delay

Exclude specific JavaScript files from delay by adding the source URL (example.js), or exclude an inline script by adding a unique string from that script. Format: one per line

Excluding JavaScript from delay
Excluding JavaScript from delay

Delay timeout

With both delay behavior options, you can set a timeout that will load scripts after a set amount of time (between 1 and 10 seconds) if no user interaction has been detected. This is optional and off by default. If you’re going to use it, we usually recommend 5 seconds or higher.

JavaScript delay timeout
JavaScript delay timeout

Here are a few examples of why you might want to set a timeout:

  1. Help improve data accuracy of tracking scripts, especially if you have a goal associated with a pageview, but maybe no user interaction. You want the goal to trigger still.
  2. You have a Google AdSense blog, and a user is opening up multiple pages in new tabs in the background. You still want the ads to fire off.

You can also modify the delay timeout further with the perfmatters_delay_js_timeout filter.

Delay inline JavaScript

To delay inline JavaScript, enter a partial string that is within the <script type="text/javascript"> </script> tag.

For example, say we have this inline JavaScript.

<script type="text/javascript">var lazyLoadInstance=new LazyLoad({elements_selector:"[loading=lazy],.perfmatters-lazy",thresholds:"200% 0px"});</script>

We can add lazyLoadInstance to the “Delay JavaScript” box and it will delay it. You can choose any string within the script tags, just make sure it’s unique.

For some JavaScript, they might have a source file as well as an inline component. In this case, you will need to delay both for it to work properly.

Examples of scripts you can delay

Below are some examples of common scripts we delay on WordPress sites.

Delay Google Analytics

To delay Google Analytics, add the following to the “Delay JavaScript” box.

ga( '
ga('
google-analytics.com/analytics.js

If you’re using our local analytics, you can also delay the scripts.

Local Perfmatters analytics.js

To delay the local Perfmatters analytics.js script, add the following to the “Delay JavaScript” box.

analytics.js

Local Perfmatters gtag.js v4

To delay the local Perfmatters gtag.js v4 script, add the following to the “Delay JavaScript” box.

gtagv4.js

Local Perfmatters Minimal

To delay the local Perfmatters analytics-minimal.js script, add the following to the “Delay JavaScript” box.

analytics-minimal.js

Delay Google Tag Manager

To delay Google Tag Manager, add the following to the “Delay JavaScript” box.

/gtm.js
/gtag/js
gtag(
/gtm-

Google Adsense

To delay Google AdSense, add the following to the “Delay JavaScript” box.

adsbygoogle.js

If you’re using a plugin like Ad Inserter, along with HTML insertion blocks, you’ll want to delay both the script and the inline portion.

adsbygoogle.js
ai_insert_code

Delay Facebook Pixel

To delay the Facebook Pixel, add the following to the “Delay JavaScript” box.

fbevents.js
fbq(
/busting/facebook-tracking/

Above are just a few of the many examples of scripts you can disable. If you are having any trouble delaying a certain script, feel free to contact us.

How to filter delayed scripts

You can use the perfmatters_delayed_scripts filter to manipulate your delayed scripts. For example, you could exclude a script from being delayed on a desktop device.

add_filter('perfmatters_delayed_scripts', function($scripts) {
     if(($key = array_search('name_of_your_script', $scripts)) !== false) {
         if(!wp_is_mobile()) {
             unset($scripts[$key]);
         }
     }
     return $scripts;
 });

You can use the perfmatters_delay_js filter to turn your delayed scripts on or off entirely. For example, you could turn off delay only on pages.

add_filter('perfmatters_delay_js', function($delay) {
      if(is_singular('page')) {
        return false;
    }
    return $delay;
});

Delay versus Defer

Defer will push the JavaScript to the bottom of the page load. This helps resolve render-blocking issues. However, the JavaScript still has to load when the page is rendered. In other words, it will still play an impact on your Core Web Vital scores when it comes to JavaScript execution time, transfer sizes, etc.

Delay removes the JavaScript from the waterfall/page load altogether. If you run a speed test, it will appear as if those scripts don’t exist. They do, but instead of loading on page load, they load on user interaction (moving mouse, scrolling, timer, etc.) This helps improve your Core Web Vital scores and improves the first contentful paint (FCP).

Regarding compatibility, defer is a practice that has been around for a long time. It’s usually safe to defer everything, which is what the Defer JavaScript feature in Perfmatters does. And then we have the exclusions box for cases where a script might need to be excluded due to load order.

Delay is a little trickier, as you can’t just delay every JavaScript file. Due to loading on interaction, it will only work on specific scripts. This can be a little trial and error, but the benefit of delay is that it’s very powerful! It has a massive impact on each script you use it on.

The good news is, you can use both delay and defer simultaneously. If both are applied to the same JavaScript file, delay will always take precedence, and defer is essentially then a fallback. If you delay all of your JavaScript, defer can still be useful as you might have delay exclusions, which would then use defer.

Troubleshooting delay

There are a few things to keep in mind when using delay, especially how it impacts certain scripts.

For example, with Google Analytics, you might see slightly lower stats if they’re delayed. That’s because the script is now loading on user interaction. However, this isn’t necessarily a bad thing. Google doesn’t filter out all of the bots or spam, so if you delay Google Analytics, along with the delay timeout feature, it might improve your data as it now narrows it down to actual users.

Bounce rate measurements might also fluctuate if you delay Google Analytics.

Was this article helpful?

Related Articles