Skip to content

How to Truly Lazy Load JavaScript in WordPress?

Watch video tutorial on YouTube.

After doing all optimization steps one of my potential clients couldn’t get high PageSpeed score on mobiles for the WordPress website. I checked their website and found that JavaScript was not lazy loaded correctly.

They were using premium plugin for all optimizations.

JavaScript was lazy loaded in theory. But in reality it was not waiting for user interaction like mouse movement, click, scroll events. It was instantly loaded and executed without any delay.

In this video tutorial I explain how true lazy loading should work.

When not done correctly WordPress website will not get faster and performance score will remain in 50-60 range.

You can see how pagespeed score changes from:

  1. Not optimized JavaScript — PageSpeed 58.
  2. Deferred — PageSpeed 57.
  3. Incorrect lazy loaded — PageSpeed 64.
  4. Correct lazy loaded — PageSpeed 100.

Which JS to lazy load?

Lazy load all JavaScript from plugins, inline jQuery, remote .js files in the Flying Scripts plugin settings.

Lazy load everything except main jquery js file

  • Lazy load external scripts like Adsense, Analytics, chat widgets, weather widgets, captcha etc.
  • Lazy load JavaScript from all plugins.
  • Lazy load all inline JavaScripts (especially those that rely on jQuery).
  • Double check loaded JS using Google Chrome Network tab and lazy load everything except main jquery file. Other scripts may rely on it (main jquery) so do not lazy load it. Otherwise your WordPress website functionality may break.

Load all those JavaScript on user interaction like:

  • Mouse movement
  • Scroll
  • Swipe
  • Click

If none of those happens then wait at least 5 seconds before loading JS.

This will give enough time for page to complete rendering. So no render blocking will happen.

You can see that I get 0ms render blocking time in PageSpeed report.

Resources mentioned in tutorial:

Leave a Reply

Your email address will not be published. Required fields are marked *