javascript

Loading JS files is critical for page rendering. However, in a lot of cases, it causes speed issues and leads to low Google PageSpeed Insights stores. That's why you need to make sure to defer JavaScript in Magento and optimize it properly.

While you can spend lots of time optimizing the code, it's not worth it. Especially when tools like Magento 2 Defer JavaScript are there to help.

So, today we'll go through the process of deferring JS in Magento step by step. You'll basically need to enable a few options and let the module do the rest. 

Ready to start?

But before we do, navigate to Stores > Configuration > Magefan Extensions > Rocket JavaScript and enable it.

Step 1: Minify and Merge JS Files

Here you need to choose whether to Minify and Merge JavaScript Files. Both options improve JS loading and optimize JS files in general.

  • Minification — the process of removing unnecessary data (blank lines, commend, delimiter, etc.) from JS files. This makes browsers to read them faster and return pages to customers faster correspondingly.
  • Merging — the process of combining multiple JS files together to reduce the number of HTTP requests to the server. This makes the server return these faster (since there are fewer of them).

magento javascript settings

Step 2: Enable Deferred JavaScript

To move all of the JavaScripts to the end (bottom) of a page, before the </html> closing tag enable a corresponding option. 

Since some JS or pages might be critical for user experience, you can set some limitations. Specify the pages on which you don't want to move the JS to the bottom — Disallowed Pages for Deferred JavaScript field.

magento 2 javascript

Besides, you can defer the loading of some JS files by specifying them in the Ignore Deferred JavaScript With field.

Step 3: Enable JS Bundling

JS bundling allows you to group JS files into bundles to reduce the number of HTTP requests to the server. The page is supposed to be returned faster. 

However, sometimes the opposite happens, especially if you have too many bundles.

So, if you want to manage JS files included in the JS bundle manually enable the JavaScript Bundling Optimization. Then enter the list of JS files you want to be Included In Bundling.

Pro tip: to reduce the size of the bundle, optimize Magento JS bundling by compiling a list of JS files from all pages.

magento 2 javascript bundling

Don't forget to Save the settings and enjoy benefits from deferred JS in Magento. However, note that JavaScript files are just a small part of the Magento speed optimization picture. 

You also need to optimize images, CSS files, HTML and caching to speed up Magento. The journey is not easy, but it's totally worth it.