How to Reduce JavaScript Execution Time? step by step process

While running a page speed test in the Lighthouse, you may have received a warning like “Reduce JavaScript execution time.” And that’s exactly why you’re reading this guide. Well, I’ll let you know everything in detail in this guide.

JavaScript can greatly affect your site’s speed, and thus, it’s crucial to optimize any type of script issue to ensure faster site speed. And reducing JavaScript execution time reduces the main-thread blocking time, which results in improving the site loading time.

It is one of the most critical recommendations, which generally refers to decreasing the amount of time spent parsing, compiling, and executing your site’s JavaScript files. But, you can do this conveniently with the proper guidance.

Therefore, read this guide to learn how to reduce JavaScript execution time along with how it can affect your site. So, let’s get into this guide.

How JavaScript Slows Down Your Page Performance?

Actually, the execution time of JavaScript is closely related to the First Input Delay score, which measures the page’s responsiveness and interactivity. So, while you try to interact with a page, but it doesn’t respond fast, it implies that the browser is taking time to load the JS files.

When the JS files take longer to load or execute, it ultimately slows down the page performance. Here’s how slow JS execution time impact the page performance-

  • With a longer loading time, users require more bytes. This way, network costs get higher.
  • JS files are compiled and parsed with the main thread. That’s why the page can’t respond to user input when the main thread is busy loading the files.
  • When the page runs huge codes before it’s really needed to load, it causes delays in the Time To Interactive. Since TTI is one of the main metrics, that makes sure how users perceive your page speed. So when it loads too late, the page speed slows down even more.
  • JavaScript files consume a lot of memory when they hold on to huge references. And when pages consume a huge number of memories, they start appearing junky and slower. In fact, memory leaks cause completely freezing up your page.

How to Reduce JavaScript Execution Time?

How to Reduce JavaScript Execution Time

Now, before you move forward to optimize your site to reduce JS execution time, you should measure the JS execution time accurately. To identify and measure it, you can use Lighthouse, or Google PageSpeed Insights, or GTmetrix.

If your URL contains any JavaScript execution time issues, the report will show a warning in the diagnostics section, like the following image.

How to Reduce JavaScript Execution Time

This audit report contains each JS script that has execution times longer than 2 seconds. As the image shows, the Lighthouse shares the execution time by Total CPU Time (the compiling stage), Script Evaluation (the parsing stage), and Script Parse (the memory cost).

Once identifying the issues, let’s find out how to reduce JavaScript execution time. So, here are the steps that you should follow to speed up your JavaScript file loading time.

1. Reduce JS Loading Time With Code Splitting

Code splitting is the way to split your JavaScript bundles into smaller files. This way, only the critical ones will execute initially during the page load. It minimized the amount of script that requires to be parsed and compiled and results in a speedier page loading time.

Before starting the splitting, you need to modify a few files to import the single method from lodash. So, replace this dependency in package.json:

"lodash": "^4.7.0",

Replace the above command with the following one-

"lodash.sortby": "^4.7.0",

After that, remove the import _ from “lodash”; with the import sortBy from “lodash.sortby”; in src/index.js, and import the specific module.

import "./style.css";
import _ from "lodash";
import sortBy from "lodash.sortby";

Lastly, update the sorted values-

form.addEventListener("submit", e => {
 e.preventDefault();
 const values = [input1.valueAsNumber, input2.valueAsNumber, input3.valueAsNumber];
 const sortedValues = _.sortBy(values);
 const sortedValues = sortBy(values);

 results.innerHTML = `
   <h2>
     ${sortedValues}
   </h2>
 `
});

There are some popular module bundles that will allow you to split your JS bundles. Such as-

So, start with removing the following top-level import for the sort method in src/index.js:

import sortBy from "lodash.sortby";

Then, import it within the event listener that fires while the button is pressed-

form.addEventListener("submit", e => {
 e.preventDefault();
 import('lodash.sortby')
   .then(module => module.default)
   .then(sortInput())
   .catch(err => { alert(err) });
});

Now, write the sortInput method at the end of the file.

const sortInput = () => {
 return (sortBy) => {
   const values = [
     input1.valueAsNumber,
     input2.valueAsNumber,
     input3.valueAsNumber
   ];
   const sortedValues = sortBy(values);

   results.innerHTML = `
     <h2>
       ${sortedValues}
     </h2>
   `
 };
}

2. Minify and Compress JS Files

You can minify and compress your JavaScript files without doing additional work by using the following tools.

Here’s how to use these tools-

  • Log in to your WordPress dashboard and go to Appearance, then navigate to the Editor
  • Open the php file, make a copy of your JavaScript codes.
  • Open any tool from the above and paste the code into the box.
  • Click the minify or compress button, and within a few seconds, you’ll get the minified or compressed file.
  • Then, paste the updated codes on your WordPress’s function.php file and click the update button.

The best part is, you can use plugins to make this process much easier. You’ll find lots of plugins out there to do this job. Some of the most popular plugins are-

3. Remove Unused JS Codes

To remove the unused JS codes first, you have to identify them. You can do this by using the Chrome DevTools coverage tab. From the coverage tab, click on the reload button to reload and start capturing the JS files.

Now, filter the coverage by selecting JavaScript to see only the JS files. And in the last column, you’ll see the JS files in two different colors. The red color implies the unused JS, and the blue color implies the used JS.

Once identifying the unused JS codes, login to your WordPress dashboard and do the following-

  • Go to the Appearance and click on the Theme Editor.
  • Then, click on the function.php just from the right sidebar.
  • Now paste the following codes to the function.php code editor box.
* so that it is after the script was enqueued.
 */
function wp_remove_scripts() {
// check if user is admin
    if (current_user_can( 'update_core' )) {
            return;
        }
    else {
    // Check for the page you want to target
    if ( is_page( 'homepage' ) ) {
        // Remove Scripts
        wp_dequeue_style( 'jquery-ui-core' );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'wp_remove_scripts', 99 );

If you’re not comfortable with coding, there is an easy way to do that. Simply use any of the following plugins to do that work for you.

4.   Apply Instant Loading With the PRPL Pattern

PRPL is the acronym that refers to the following combination of 4 key methods, which helps make the web page load faster and become more interactive.

  • P- Preloading the most important JS files.
  • R- Rendering the initial route as soon as possible.
  • P- Pre-caching the remaining assets.
  • L- Lazy loading other routes and non-critical assets.

So, let’s see how can you apply instant loading with the PRPL pattern-

 Preloading Important JavaScript Files

You can implement preload simply by adding a <link> tag with rel=“preload” to the <head> of the document.

<head>
 <link rel="preload" as="script" href="critical.js">
</head>

Rendering the First Paint as Soon as Possible

You can ensure rendering the first paint as soon as possible by eliminating the render-blocking resources. To eliminate render-blocking on scripts, you can inline the critical JavaScript and defer the noncritical JavaScript.

If your external scripts are small, then inline their content directly into the HTML: document to avoid latency in page loading. Initially, your HTML document may look like the following-

html>
  <head>
    <script type="text/javascript" src="small.js"></script>
  </head>
  <body>
    <div>
      Hello, world!
    </div>
  </body>
</html>

Simply inline the script as follows-

<html>
  <head>
    <script type="text/javascript">
      /* contents of a small JavaScript file */
    </script>
  </head>
  <body>
    <div>
      Hello, world!
    </div>
  </body>
</html>

Once you inline the script content, it will eliminate the external request for small.js. This will help the browser to deliver a faster time to render.

Another way is to add async or defer attributes. Deferring the JavaScript files lets the browser load them only when the page’s rendering is done. So, for <scripts> tags, add async or defer to the tag.

<script src="/scripts/functionality.js" async></script>
<script src="/scripts/functionality.js" defer></script>

Pre-Caching Assets

To simplify this process, you can use a third-party library like Workbox. It comes with an array of tools to help you in pre-caching your sire’s assets.

Lazy-Loading JavaScript Files

Lazy loading is the process of loading resources only when they are needed, instead of advanced loading. When it comes to lazy loading images in JavaScript, Lazysizes is the most popular library that has been used by many webmasters. The process is really simple.

You just need to add the lazysizes script to your pages.

<script src="lazysizes.min.js" async></script>

Update your <img> tag, which may look like this- <img src=”flower.jpg” alt=””>  with the data-src and class=“lazyload” tag.

<img data-src="flower.jpg" class="lazyload" alt="">

Lastly, update the <picture> tags, by adding the lazyload class to the <img> tag and changing the <source> tag srcset attribute to data-srcset.

The tags may look like the following before,

<picture>
 <source type="image/webp" srcset="flower.webp">
 <source type="image/jpeg" srcset="flower.jpg">
 <img src="flower.jpg" alt="">
</picture>

Now, replace the above tags like the following one-

<picture>
 <source type="image/webp" data-srcset="flower.webp">
 <source type="image/jpeg" data-srcset="flower.jpg">
 <img data-src="flower.jpg" class="lazyload" alt="">
</picture>

5. Using Plugins

Some people don’t feel comfortable handling the coding. In that case, several plugins are out there to make things easiest for you in this process. Here are some top-performing plugins-

Other Considerations to Reduce JavaScript Execution Time

There are some other useful recommendations that you can consider, keeping your site load faster. For instant,

  • Avoid installing plugins and widgets that require a lot of JavaScript.
  • You should use static images instead of a slider.
  • Try not to overuse social network widgets in your sidebar.
  • Do not overuse 3rd party resources like trackers, ads, personalization layers, and A/B testing.

Conclusion

If you want more traffic from Google, you need to be ranked top in Google. And one of the major steps that can help you to rank is your faster page speed. In that case, reducing JavaScript execution time works great to improve your site’s FID score and boost the speed score.

In this guide, I’ve shared how to reduce JavaScript execution time in detail with all the easy but major steps. Hopefully, you found this guide helpful while optimizing your site for reducing JS execution time.

You can share your thoughts with me by commenting below. Also, you can Contact Us with any sort of site speed-related issues. We’re always there to help you out.

Leave a Comment