Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Magento 2 Speed Optimization | The Ultimate Guide

Running an eCommerce Store on Magento is surely not a small deal. It was one of the ten most popular platforms in 2021 for eCommerce. Every year, it handles more than $155 billion in transactions. Despite the popularity, one thing you cannot overlook is that this platform isn’t lightweight. This is why Magento 2 speed optimization is crucial if you have a Magento store.

After all, the intention behind Magento 2 was to serve thousands of users at once. Thus, if you haven’t properly optimized your Magento store, you may end up showcasing an unattractive and non-intuitive website.

An eCommerce store that loads slowly can easily be an irritant to visitors and can affect conversions negatively. More so, poor speed is even worse for the SEO rankings. Having said that, fortunately, there are several ways to tweak the performance of your platform. 

So, without juggling around anymore, let’s explore this comprehensive and ultimate guide on Magento 2 speed optimization.

Boost Your Magento 2 Store Performance

Jotted down below are some useful and efficient tips to boost your Magento 2 store performance. Let’s get started. 

Website Performance Check

Before you move forward making any alterations, changes, or fixes to the store, you must be wary of its current performance. It’s undeniable that your eCommerce would have several pages. However, checking each one of them could be a tiresome task. 

Thus, you can begin with the primary ones as they’d be most frequently visited by visitors, such as:

  • Homepage
  • Category page
  • Checkout
  • Cart
  • Product pages

Your first step should be to run Google PageSpeed Insights tests for the pages mentioned above. This test will provide you with scores with results. If anything is marked in red or orange, the speed of the page is poor. 

And then, glance at the Core Web Vitals assessment scores. Once again, the orange and red are the signs of poor performance. These metrics are a part of the new Google page experience algorithm that eventually impacts the SEO ranking. Thus, optimizing Magento Core Web Vitals properly is vital to gaining a better search ranking. 

Evaluate the Server Response Time

Moving on, you must figure out the time server is taking to respond. Time to First Byte (TTFB) comprehends the time when the server sends its first byte to the browser. It’s recommended that you check it without a full-page cache. 

In this situation, if the response time doesn’t come out to be less than a second, it isn’t a good metric. This simply means that the coding is causing a huge load on the server. And, every time the cache gets flushed, your visitors will have to wait a long time.

Thus, if your eCommerce store features hundreds and thousands of products, the entire full-page cache may not get enough time to be generated. Thus, optimize the site so that it can work quickly without the support of a full-page cache. 

However, in case you’re checking TTFB with a full-page cache, you should generally aim for a time that is below 100 ms. 

You can evaluate the TTFB through the Chrome developer console. Here are some steps to follow:

  • Visit your store
  • Open the developer console in Chrome
  • Visit the Network tab
  • Sort by Waterfall and hover the cursor on the first entry

And there, you can have your results. 

Core Web Vitals Check

Core Web Vitals are referred to as speed metrics that are part of the Page Experience signals of Google. They are generally used to evaluate user experience. The metrics use Largest Contentful Paint (LCP) to assess the visual load, First Input Delay (FID) to measure interactivity, and Cumulative Layout Shift (CLS) to measure visual stability.

Since May 2021, both the core web vital metrics and mobile page experience have been used to rank pages. As of February 2022, desktop signals have also been included in it. One of the straightforward ways to evaluate the metrics for your website is by using the Core Web Vitals report feature in Google Search Console. 

With this report, you get to see how the web pages have been categorized. Are they under the “good URLs”, “URLs need improvement”, or “poor URLS” category? For these categories, here’s the threshold:

FactorGoodNeeds ImprovementPoor
LCP>4 seconds
FID>300 ms
CLS>0.25

The core web vital metrics have been divided between desktop and mobile. 

  • Core Web Vitals – Desktop

These are the signals that are used specifically for desktop rankings. 

  • Core Web Vitals – Mobile

These are the signals that are used specifically for mobile rankings. 

Components of Core Web Vitals

Jotted down below are some of the important components of core web vitals:

  • Largest Contentful Pain (LCP) – Visual Load

This is the single largest visible element that is loaded in the viewport. Usually, it could be a featured image or a

tag. However, apart from this, it could also be:
  • element
  • Blocks of text
  • element in an element
  • Background image loaded with the url() function
  • Image inside a

and

  • Cumulative Layout Shift (CLS) – Visual Stability

This factor evaluates how elements move around or the stability of the page layout. It considers the size of the content and the distance it moves. Earlier, it continued evaluating even once the initial page had loaded. However, now, it’s limited to a five-second time frame where the majority of the shift takes place.

Some of the common CLS causes are:

  • Images without dimensions
  • Applying styles or fonts late in the load
  • Iframes, embeds, and ads without dimensions
  • Injecting content with JavaScript
  • First Input Delay (FID) – Interactivity

This is the time from when your visitors get to interact with your web pages to when the pages respond. You can also consider it as responsiveness. Some of the examples include:

  • Clicking on a button or a link
  • Clicking a checkbox
  • Inputting text into a blank field 
  • Choosing a dropdown menu

Make Possible Upgrades

By making some upgrades to your Magento 2 store, you can boost its performance substantially. Let’s know-how. 

  • Update Magento 2 to the Latest Stable Version

One of the things to consider is that Magento 2.0 isn’t the latest version. The platform continues to release new versions after almost every three months. With each new release, you get performance upgrades; thus, sticking to an older version isn’t a wise choice. 

Why should you upgrade?

Upgrading your online store to the latest version means you get more security fixes, bug fixes, and features. And then, with every update, the performance gets better. Regular updates are essential for Magento 2 speed optimization.

How to upgrade to the latest version?

Currently, the latest version of Magento is 2.4.4. Here, you can check Magento versions. Know that upgrading to a new version could be a tricky process. For example, if there are customization errors in your store, upgrading to the next version can lead to issues and problems. Thus, if you wish to upgrade without any hassles, it’s better you seek experts’ help. 

  • Make Sure Your Magento Store Uses Suitable Hosting

Believe it or not, Magento consumes loads of resources. If you’re using shared hosting, it can slow down your entire store. Most of the issues come up when there is a sudden spike in the load. 

When it comes to handling one or two users, almost any hosting can do it seamlessly. However, when the traffic starts piling up, the capacity doesn’t turn out to be enough. With every new visitor, server requests get stacked in a queue. Thus, every visitor has to wait before the preceding request gets executed. 

Why should you choose suitable hosting?

Since you’re selling products on the internet, it’s obvious that the traffic to your store will eventually increase. Hence, increasing the server capacity lets you optimize the Magento store and serve more visitors. This way, requests will not accumulate, and your site will perform better.

How to choose a suitable hosting?

First and foremost, you must make sure that your hosting is capable of meeting the minimum requirements of the Magento store. You can go through those requirements here. If you think everything is up-to-the-mark, comprehending whether changing the Magento web hosting would be worth it. 

You can make this decision on the basis of:

  • The number of visitors your site receives and the load it can handle
  • How many resources does one visitor require, including the time spent by a visitor on the site?
  • How can resources be distributed? 

For example, if your 8 GB of RAM and dual-processor server can handle 100 parallel requests without full-page cache, to process 1000 requests, you’ll require ten times more robust hardware. 

Also, ensure that your RAM and CPU are below the 80% user rate. The remaining 20% window will provide you satisfactory flexibility to handle occasional traffic spikes while not straining your budget. 

  • Use HTTP/2 Instead of HTTP/1.x

Magento has a huge number of static files, such as media files, CSS, JS, and more. If you’re using HTTP/1, it would have created a new server connection for each file. On the other hand, using HTTP/2 can process an array of files in one connection. 

Why should you use HTTP/2?

For Magento, HTTP/2 offers varying abilities, such as:

  • Compress headers
  • Working in parallel on a single, individual connection
  • Using multiple server requests simultaneously

As a result, a lot of time is saved. Thus, your Magento website is ultimately sped up. 

How to switch to HTTP/2

Approximately 99% of web hosting Magento servers (be it Nginx 1.9.5+, Apache 2.4.17+, etc.) are supporting HTTP/2 by default. The same is the case with CDN providers (be it KeyCDN, MaxCDN, Cloudflare, etc.).

Find out whether HTTP/2 is enabled in your server settings or not. You can use this Chrome extension to discover the same. If it isn’t supported, you can get this job done by a professional. 

  • Switch to an Optimal PHP Version

Every new PHP version performs better than the last one. If you aren’t using the latest PHP 7.4 version, it’s better that you switch to it sooner than later. 

Why should you switch?

Using PHP 7.4 will offer you better speed and stability than the previous version. The code will perform quicker, thus, decreasing the time to the first byte. 

Profile and Review All Third-Party Extensions

Typically, default Magento with basic data can perform well. The real problem starts to come up when you add third-party extensions and additional modules, which generally slow down the entire store.

Some other problems may come up because of heaps of data or because you’ve got a lot of elements on pages, such as sliders or widgets. One thing to keep in mind is that using multiple extensions from diverse vendors can substantially decrease the performance of your store.

The reason behind this is that every module generally works autonomously. It requests the required data again, even if some other module has requested it already. With every added extension, you’ll be slowing down your code. 

This turns out to be bad because extension developers have created their products to fulfill unanimous requirements. And, they haven’t been built specifically for your store. Thus, unoptimized extensions can create more problems down the line. 

How to profile and review third-party extensions?

To deal with this issue, you should begin by investigating everything about your store. Determine the points that are slowing down your store. Understand whether you require all the plugins or not. Once done, you can either remove the extensions or optimize them to meet your needs. 

  • Review Page Performance with Magento Profiler (Or Other Profilers)

To determine exactly what is slowing down your Magento website, you must begin with evaluating the site performance. And then, on the basis of your discoveries, you’ll get to decide which plugins, modules, extensions, etc., are worth getting rid of or optimizing. 

You can get this information through a profiler. There are a few potential ways with profilers:

  • Choose Magento Profiler

It is an inbuilt tool that you can use to evaluate database queries and the calls of several methods. Magento Profiler is wonderful at discovering slowdowns, bottlenecks, and other concealed issues related to Magento performance.

Moreover, the tool doesn’t need any extra profiling extensions and can be used independently. However, keep in mind that profiling through this method is available when specific logic is present in the code.

Such logic is already given by default, and you can add your own if you want. For example, this could be the situation with functions that call execution time measurement. Sure, there are many ways to enable a Magento Profiler. However, if you haven’t worked with this factor before, it’s better you seek professional help.

  • Specialized Extensions

You can also use specialized extensions to work with Magento Profiler. They expand the features and offer more comprehensive results. Some such tools are:

  • Mirasvit Module Profiler

This one is a simple and easy to use the add-on. It provides a timeline that displays such areas in the store that are not performing adequately and need attention.

  • MGT Developer Toolbar

This is another free add-on tool that you can use for Magento Profiling. It is quite similar to the previous one and uses the same technology as well. The only difference between both is that this one offers broader and better data representation, improved inspection, and other additional features. 

  • Detailed Profiling

If you want to get profound and detailed profiling, you can go with PHP Xdebug Profiler. This tool works at the PHP level and outside Magento. It accumulates data during the execution of PHP scripts. 

Unlike the other tools, it offers highly detailed data on calls, even if you have millions of them. You can narrow down the issues and then work on them accordingly to speed up your Magento store. 

  • Optimize or Remove Your Plugins, Event Observers, etc

The profiling process would have resulted in you receiving data on the problematic areas of your site that are causing performance issues. By now, you’d know which event observer, plugin, module, class, file, etc., have problems.

So now, you have two options. You can either optimize some things or get rid of them to improve the performance. 

How can you do it?

By following the below-mentioned steps:

  • Remove Plugins

Uninstalling plugins wouldn’t be a frequent thing for you. Usually, store owners install everything they need, and most likely, they pay for these plugins. However, if you have anything you don’t use, discarding them would be the right decision.

It’s also recommended that you eradicate such plugins that create several logs on pages. For example, you may have 3-4 modules for health checking of the site. In case something is not right, you’re notified, and a corresponding record is created in the log. Such modules create a load of unwanted logs and tests, thus, building a time-consuming process that can take up almost 15% of the page load time.

Thus, to avoid this issue, start by looking out for a simpler and easier alternative to keep logging only for critical errors and not for everything. 

How to uninstall Magento plugins?

If you wish to uninstall a module, know that a plugin could be located in various directories. It could be the Vendor folder or in the app/code. Based on that, you can follow the following tips for deleting the plugin:

  • Method 1: app / code (bin/Magento)

To disable and delete the plugin in Magento 2, you can use SSH with the below-mentioned commands. In this example, we’re using TestModule:

  • For Developer Mode

bin/magento module:disable TestModule –clear-static-content

bin/magento setup: upgrade

cd app/code/TestModule/

rm -rf TestModule

  • For Production Mode

bin/magento maintenance:enable
bin/magento module:disable TestModule –clear-static-content
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy en_US de_DE
bin/magento maintenance:disable
cd app/code/TestModule/
rm -rf TestModule

  • Method 2: Removing Extensions via Composer

Here are some steps to remove the plugin through composer:

  • Log into the domain through SSH/CLI
  • Go to the store’s root
  • Acquire a list of enabled modules through this command: bin/magento module:status to find the module you wish to remove
  • If you want to simply disable the module, use the command: bin/*plugin name*: disable *plugin name*_Demo
  • If you wish to remove the module from every activity of the website, use the command: bin/magento setup: upgrade
  • Visit the root directory of the module and look for the composer.json file, like vendor/*plugin name*/module-demo/composer.json
  • Lastly, get to the root of your website and run the command: composer remove *plugin name*/module-demo

Things to Keep in Mind When Removing Magento Extensions

You can have anywhere between 5-10 plugins or extensions. Thus, when you discard a module, ensure that you’re deleting a certain one rather than the whole vendor folder. 

Note that you can delete different extensions that have one common extension serving as the foundation. If all of the extensions are situated in the same folder, rm – rf TestModule will end up deleting everything and not just the only one you wanted to delete. 

  • Optimize Plugins

If you don’t wish to remove any plugins, it’s better you begin optimizing them. Having plugins isn’t an issue; the primary problem is in their code. As mentioned above, developers sell plugins as a universal solution; thus, they don’t optimize these tools significantly. 

Often, plugins aren’t tested on a huge data scope when created. Therefore, there are high chances of you facing issues as the logic of a plugin can slow down the store. While such a problem can be handled when you have only a few products on the site, if you’re running a store with thousands of products, you surely have to optimize the plugins. 

Potential Issues Arising During the Process of Magento Optimization

When optimizing the Magento code, you can face a variety of issues. These could be concerning the performance of your helpers, modules, event observers, plugins, and more. Here are a few of them:

  • No Caching on the Class Methods’ Level

Let’s suppose that a store page is showing something 30 times using the same data. If you aren’t using caching, this data will get requested 30 times to get the same result. Duplicate calls consume a lot of time. Thus, rather than having 30 requests, your store can narrow it to one variable that will return data in succeeding calls. This can be done through caching.

  • Executing Unwanted Logic in the Class Constructor

There are situations when a specific code is required only in one certain method and not all the time. But, other methods of the class could be used during page load. Simultaneously, the constructor will always get executed when a class instance is created. This, in turn, results in the class of unwanted logic that will negatively impact the performance.

One solution is putting the code from the constructor to the method. This way, it will be executed only when required. If it gets executed every time, it will consume a lot of time. Sure, removing logic from the constructors is not necessary. 

  • Lack of Caching for Blocks Present on Pages

Some specific page elements are showcased across the entire website, such as the menu with dropdown sections and lists. Generally, the menu comprises product categories. When there is a lack of caching for such blocks, they load from scratch every time somebody clicks, which is time-consuming. 

In the image below, you can find an example. The general page timeline takes 753.3 ms to load. The black rectangle displays how long it takes to load one specific block showcased on every page. Such a code can be cached to improve performance. 

  • Event Observers in Magento

Magento 2 is stepping aside from observers and asking developers to use plugins. However, for now, both the tools are available in the system. The event observers are connected to specific events and can dispatch them whenever required by an Event Manager. 

But currently, observers have restricted capabilities and are generally available in Magento 2 as a legacy tool. Nevertheless, a few developers use events and observers to extend the functionality with custom code.

While event observers are still present in Magento 2, they shouldn’t be your first choice. Experts recommend not to use them to keep the performance of the store steady.

  • Problems with Plugins

With plugins, you can experience several problems. Most of them will be situations where the performance will be slowing down because of the integration with your eCommerce store and its custom individualities. Yet, the most prevalent issue is loading a large amount of data in the plugin.

Static Content Optimization (CSS, JS, Images)

Most of the content that your browser downloads are graphic elements and pictures. So, here are a few ways to speed up Magento 2 by optimizing this static content. 

  • Make Visible Content a Priority

Visible content, also known as above-the-fold content, is the first part of your store’s page that visitors see before scrolling down. To some extent, visible content parameters are considered by Google PageSpeed. If you haven’t optimized it, the impact will be on the user experience. 

Why should you optimize visible content?

This should be done to improve the user experience of the store. Since this content type loads and displays the first, it’s obvious to make it a priority.

How to optimize visible content?

  • You can begin by putting above-the-fold content before anything else. This can be done by evaluating and checking the HTML of every page to see if it’s coming first.
  • Next, optimize the content’s size. Pay attention to media, compress pictures and get rid of anything that’s unnecessary. 
  • Revise the above-the-fold content’s rules in the CSS files and JavaScript. Generally, all the CSS and JS get moved to the bottom, and vital styles are left at the top. The objective here is to decrease the time and the need of the browser to analyze the section of the page.
  • Optimize CSS for Faster Load Times

When it comes to CSS optimization, there is a lot that you can do. Unfortunately, often pages are overworked with CSS styles. This causes a drop in performance. Sometimes, CSS styles that are written for a certain page get placed together with the rest of the communal CSS. This causes the entire CSS file, which is loaded all every page, to become heavier. 

Additionally, unused CSS styles create an issue as they take up space and increase the download time. Thus, the more unnecessary CSS styles you’ll be using, the longer the files will take to load. 

How can you do it?

There are several ways to optimize CSS. Some of them include:

  • Merging and Minifying

This method substantially decreases the number of requests to the server. Also, it compresses the size of the CSS files, courtesy of minifying, which eradicates unnecessary spaces. 

There are a few tricks that can be implemented from your Magento Admin Panel to accomplish this, like:

Through Developer Mode

  • To access these settings, switch to the Developer mode. Fire the SSH and type:

php bin/magento deploy:mode:set developer

  • Visit the Stores and click on Configuration
  • Click Advanced and then on Developer to get the CSS settings
  • Set both of them to Yes

This tool will shorten and optimize the existing CSS code to assist the browser in downloading it faster. 

Merge, on the other hand, is useful as it helps browsers in maintaining only a certain number of connections per server. A few of the big files will be downloaded quicker than a lot of small ones. 

  • Without the Developer Mode

This one is a simpler way to address the Merge and Minify. If you don’t want to use the above-mentioned method, you can go with the following command. They will let you do the same thing without using the developer mode again and again. However, to use this method, you’ll have to clear the Magento cache. 

bin/magento config:set dev/css/merge_css_files 1
bin/magento config:set dev/css/minify_files 1

  • Defer Non-Critical CSS Styles

You can divide CSS styles into two categories: non-critical and critical. The non-critical CSS styles are generally used post the initial load as they take more time to render. On the other hand, critical styles are used to not make the visible content look broken whenever the page is opened. 

This deferring non-critical style method works along with the Merge and Minify method. So, the CSS that was earlier merged and minified is put off for after-loading. This simply means that non-critical styles will get loaded once the full-page content has loaded. 

To accomplish this, you’ll have to put non-critical styles at the bottom of a page. They will get initiated upon a certain event, like an unload JavaScript event, or until a visitor begins scrolling the page.

  • Creating Critical Styles

As mentioned above, your store’s page is going to look broken in case the non-critical styles are deferred. This is done to decrease the initial page loading time. Thus, you’ll have to create critical styles for the page’s first part that’s visible when opening a website.

Critical CSS is generally inserted directly inside a page through inline styles. This enables the first-seen content to appear good. Additionally, critical styles keep everything static on the page, which positively improves the performance. 

  • Splitting Styles by Specific Page Types and Deleting Unused Styles

Next, you must pay attention to the changes made in the design of the elements. Typically, not all the old styles get removed in the course of redesigning the site. Such unused styles can gather up and create a complete set of CSS that isn’t applied anywhere.

They consume space and unnecessarily add heaviness to the overall CSS file, slowing down the page load. Thus, you must audit the styles and remove unwanted bloat. 

There are several scenarios when all the CSS styles accumulate and load on all pages. Nonetheless, it’s good to separate the styles needed for one certain page type with a unique design. Such a CSS is neither added to the common structure nor in the shared styles. 

  • Optimize JavaScript

JavaScript optimization is one of the significant things to do to boost the performance of your store. There are chances that you’d have to rewrite JavaScript parts as it takes a lot of space because of several changes on the page. Or, there could be heavy JavaScript logic that takes up the whole RAM. If anyone is the case, here are some tips to fix the issue. 

  • Delete Unused Scripts and Shift Everything Else to the Bottom

One of the best ways to optimize Magento websites is to remove all the unused scripts from the store and shift the remaining ones to the end of the page. 

During the process of page loading, the browser reads the page as different parts – the head and the body. The browser reads the code from start to end. Sometimes, it also waits to download certain JS files before moving down the page. 

Of course, this is a generalization. Your browser will be trying to optimize the entire process to a great extent by downloading files simultaneously and more. However, you can make it even more straightforward by following these steps:

  • Find out if there is JavaScript code on the store’s page that is not going to be executed ever; if yes, simply remove it.
  • Next, move the user code to the bottom of the page. By doing so, the code will not block static content from loading. This will result in improved page render speed. 

Your store visitors will get to read the text and see pictures even before the entire page is rendered. 

  • Standard JavaScript Optimization Cases

Moving forward, let’s find some basic scenarios of JavaScript optimization that can help you speed up the site and enhance render speed. 

  • jquery.ready

jquery.ready can help load all the JavaScript functions the moment the page DOM turns safe to operate. This means that rather than serving meaningful content to visitors, the browser will be waiting for JavaScript code to load, consuming time and being a deterrent to the user experience. 

More so, it’s specifically annoying for such functions that are CPU-heavy and can completely disturb a smooth process of page loading. Thus, the solution here could be to avoid non-critical, CPU-intensive JavaScript code from running in .ready().

Rather than crowding all the functions into one handler, you can go with a more flexible approach. As an effective mid-way where you get to balance content delivery times and JavaScript code loading together, you can use $ (window) . ready ( ) and $ (window) . load ( ). 

  • Intervals and Timeouts

Heavy JS code can be separated into small bits with mini-intervals. For extra flexibility, you can evaluate how much time the browser is taking to execute a CPU-heavy code. And then, you can reduce or add the amount of work for the following batch.

For example, the first batch is 100 lines. However, based on the performance of the browser, you can give instructions to execute a workload of either 80 or 300 lines for the visit next time. 

Generally, for this objective, setInterval (func, delay) and setTimeout (func, delay) are the primary methods that can help break down heavy JavaScript into small parts. Moreover, if you want the code to modify delay flexibly, you can use recursive setTimeout rather than setInterval. 

  • Delay the Initialization of JS on Scroll

It’s obvious that initializing any widget or component takes a lot of time. The reason behind this is the rebuilding of the HTML structure. During this process, a few elements get pulled, and there could be extra connections. If you leave everything in a one-page load thread, you’re sure to come across slow JS execution. 

In certain scenarios, JavaScript works synchronously and step-by-step. In others, it works asynchronously. However, altogether, it can slow down the performance. To tackle this problem, you can delay the initialization of JS until the visitor begins scrolling down a page. 

Let’s suppose that a few parts of a page aren’t visible. Also, they shouldn’t be visible right away either. For example, somewhere towards the bottom of the page, you can have a slider. In this situation, it won’t be important to load it instantly. Sure, your browser will see the JavaScript for the slider as it receives the entire page’s content. However, you can initialize a load of this slider only when the visitor begins scrolling. So, by the time the visitor scrolls to the area that has the slider, the content will be loaded already. 

The below-mentioned code showcases how you can add a scroll event. The func part demonstrates the logic that gets executed on a scroll trigger. However, there could be some other options as well, such as connecting something, initializing the slider, etc. 

window.addEventListener (‘scroll’ , func);

  • Eliminating Heavy JavaScript Logic

To make a store page look eye-catching, restructuring HTML is one of the tedious processes. This is even one of the primary responsibilities of JavaScript. However, if JavaScript isn’t ideal, the performance will suffer. One thing to note here is that you can create JS non-optimally from the start.

You can begin JavaScript optimization by looking for ways to decrease page restructuring and perform fewer document searches. Another workaround here can be delaying the initialization of JavaScript on scroll. 

And then delaying AJAX requests is another required optimization step. All the AJAX requests have a vital effect on the performance, specifically the external URLs. There are two major reasons why you should e delaying AJAX requests on a timeout or a scroll such as:

  • If a website is spending a lot of time just waiting to get and process AJAX requests, Google PageSpeed will simply regard the site as a slow one.
  • In case the AJAX requests are to third-party services, they may get results with not just code. For instance, they might get the connection of additional styles, fonts, media, etc., further putting the burden on the site.

For instance, there is a possibility that your store might be using a live chat module from a third party. This service can offer a link with a JS file path. Considering that it’s an external URL, a huge amount of time will be spent on connecting and downloading the required files as they’re available on varying servers.

However, there’s a chance that your visitors may not require a live chat instantly. Thus, to improve the page loading, you can delay this script for the time being.

  • Make Use of JavaScript Bundling Adequately

To enhance the loading process, Magento tries to put all the JavaScript files into some big bundles. However, JavaScript bundling averts page load until the browser has finished downloading the JS bundles.

Generally, JavaScript bundles can be of more than 10 MB in size. They are huge in comparison to CSS. Thus, merging JavaScript doesn’t seem to be an ideal option as Magento loads these bundles whenever the browser has requested a new page. 

The fixing of JavaScript Bundling works amazingly along with Content Delivery Network (CDN) upgrade. Smaller JavaScript files make individual pages much lighter. Moreover, CDN looks after the delivery of these small files to customers. 

So, in the developer mode, to ensure that the Magento JavaScript settings are adequate, follow these steps:

  • Visit Stores and click on Configuration
  • Go to Advanced and click Developer
  • Click JS Settings
  • Set the JavaScript

During this, Bundling and JS Merge should be Off. Also, JS minification should be On.

  • Enable HTML Minification

If you update content on your Magento store quite often, it’s recommended that you minify HTML. This will help in Magento 2 speed optimization by speeding up the loading of documents and decreasing the page size. 

Also, minifying HTML cuts developer comments, replace variable names with shorter ones, and cleans up the code to decrease clutter. 

How can you do it?

Minify HTML is an option that you can only find in developer mode. Here are the steps to follow:

  • Go to Stores and click Configuration
  • Choose Advanced and the Developer
  • Click Template Settings
  • Here, tick off the Use System Value option to access the Minify HTML option
  • Set this one to Yes

And you’re done.

  • Optimize Your Images & Media Files

Media files can take a lot of time to load. This is the reason why several techniques are used to improve media content loading. Let’s find out some of them here:

  • Use Lazy Loading for Images to Optimize Speed

A chosen method for page loading order provides a substantial performance boost without huge investments. Lazy loading is an apparent performance pattern that helps load GIFs, images, and other heavy media when they step into the viewport. This simply means that the browser won’t try to load the entire page instantly. Rather, it’ll give priority to loading visible content.

As a visitor scrolls towards the end of the page, new content will get loaded on the move. To begin with, lazy loading displays a lower-resolution picture or a placeholder image. And then, it switches on to the high-quality source image. 

For a visitor, the integration of lazy loading means:

  • A smooth performance, specifically on tight bandwidths and low-end devices
  • Quick image loading for media that visitors already see in the viewport

For your Magento store, lazy loading means:

  • Improved perceived page load speed
  • Implementations that are SEO-friendly
  • Savings of bandwidth

However, you should stay cautious of lazy loading. By default, this option is enabled for Magento 2 optimization for all the images on pages. However, it shouldn’t be applied to the content that’s above the fold, as images here should be showcased right away. Thus, ensure that lazy loading is only applied to images in the dropdown menu and below-the-fold content.

  • Use HTML Tag for Performance Tuning

The HTML tag is quite effective for responsive designs and pages that have a lot of images. Through this tag, you can easily define several image sources in a single . The right selection of images will be based upon the min-width parameter and the viewport of the image.

This turns out advantageous when you wish to provide the browser with the capability to select the best fitting picture for a specific dimension. One of the most prevalent examples would be the mobile vs desktop browsing experience, where the viewport value fluctuates a bit. So, this works well when optimizing Magento stores for mobile visitors.

Also, it could be time-intensive to integrate tags from the scratch for the entire site. You’ll also have to make other extensions familiar with how to work adequately with the tag. So, to help you out, here’s a sample code regarding how it can be done:

  • Get a CDN to Quicken Content Delivery

The Content Delivery Network (CDN) assists you in speeding up content delivery by caching the files on remote servers and catering to every user from the bordering server to them. 

Using a CDN is one of the best Magento 2 speed optimization strategies. It helps you enhance the site speed when you have a diverse target audience and serve customers from across the world. The CDN makes sure everybody gets to access the store at a similar high-speed, regardless of where you’re hosting the store.

How does a CDN work?

While a CDN comprises servers that host the content, it is incapable of serving as a web host itself. You’d need traditional web hosting to operate the store. Basically, the CDN will just hold your site’s content on servers closer to the end-users. It refers to the original, main site’s content that’s stored on the original store if you make any updates or changes. 

Your original store could be a real, on-premises server located wherever your business has its headquarters. However, several growing businesses choose to use cloud storage providers to cater as their origin store. With this option, you get to scale down or up as site content grows and only pay for what’s needed instead of investing in expensive networking equipment and on-premises servers. 

The CDN provider sets the edge servers at internet exchange points (IXPs). These IXPs are points where traffic flows between varying internet service providers. Not all the content will stay stored on IXPs all the time. A visitor would have to request that site content first. Once the CDN has retrieved it from the origin store to the nearest end user, it keeps the content on that server for as long as the content gets requests. 

Every content always has a certain Time to Live (TTL) on the server. This TTL defines how long the edge server will keep the content. At a point, if the content doesn’t get requests within the TTL, the server halts storing it.

When a visitor pulls the site content from the cache on this edge server, it’s called a cache hit. When the content isn’t in the cache and has to be fetched from the origin store, it’s called a cache miss. The ratio of hits to misses is called the cache hit ratio. It’s a vital metric for site owners who’re using cloud storage as the origin and are trying to optimize the egress fees (which are the fees that cloud storage providers charge in order to send data out of the systems). The better the ratio, the less they’ll have to pay.

Moreover, a CDN is a good alternative to moving the server physically. Just keep in mind that you’ll experience a lot of benefits from a CDN only if your store is installed on-premise. 

In this situation, you’ve got a few different options, such as:

  • Using Cloudflare

If you’re a new user, Cloudflare is a recommended option for you. It can compress and resize images. Also, it lets you set caching rules. Not just that, it’s easy to install and user-friendly as well. 

  • Simply register for a new Cloudflare account
  • And add the site when prompted

Keep in mind that you’ll need the login and password of your registrar as some part of the entire configuration process is done outside Cloudflare and at the admin panel of your registrar. 

  • So, log into the registrar’s account
  • Go to the nameserver configuration tab
  • Write the current name servers
  • Change them to the ones that you got from Cloudflare
  • Save changes

And then, check the domain to ensure Cloudflare nameservers are up and running. It may take some time to get updated. In some situations, it can take up to 72 hours. So, keep checking.

  • Renting a Server

Contrary to the above scenario, if you don’t have a diverse customer base, you can rent the server from the country where a majority of your visitors reside. The closer your servers will be to the visitors, the faster your site will load for them. Know that latency is based significantly on routing and distance.

  • Use Magento Gzip Compression

If the responses of the server aren’t compressed, the transmitted data’s size could be larger than required. Yet, in case the compression takes place during runtime, this could lead to overhead resource consumption, which further decreases the speed of the site and impacts the performance.

How does using Magento Gzip compression help?

Compression is the substance of a store that is performance-oriented. This technique for Magento performance optimization can be used to give a boost to the delivery speed and decrease resource consumption. The solution provides an exciting comprises between Time to First Byte and bandwidth reduction.

For the uninitiated ones, Gzip compression is a web server function that is used for compressing content. It decreases the size of each file that a visitor requests from the server. For instance, a 60 KB file is going to be forwarded to your browser as an 8 KB Gzip archive. This could be compared to when you send data in archived ZIP files as they have less weight.

As an alternate option, you can use Brotli compression as well. This is a modernized and analogous algorithm that was developed by Google. This solution is adequate for several browsers and is optimum for compressing textual data. The major differentiating factor of this one from Gzip is that it makes use of a dictionary, returning keys rather than full keywords. Thus, files that are compressed through Brotli can be almost 15% smaller than the ones compressed with Gzip.

How is it done?

The Gzip compression can be integrated in a variety of ways, including through Apache or NGINX. Let’s take up NGINX as it’s user-friendly. It looks after compression before offering responses to visitors. Thus, it doesn’t impact the performance of your Magento store in any way.

Plus, it doesn’t compress server responses the second time if it was regulated before by a proxied server. Be aware that compression consumes CPU time. This means that your web server will be comprised between fetch time and data savings.

A lot of environments do support the module of Gzip from the get-go. However, it’s almost unlikely that you’ll get to configure NGINX on your own. However, fortunately, Gzip compression comes included in the hosting settings a lot of times. Thus, to make sure it’s running on your site, you’ll have to ask the hosting provider to turn Gzip compression on.

Database & Search Updates

Another way to improve the Magento 2 performance is by clearing the database logs of the store and optimizing the search. Let’s find out how:

  • Stop Using Flat Catalogs

For years altogether, switching to a flat catalog has been regarded as one of the best practices for boosting performance. This setting can be found in both Magento 1. x.x and Magento 2. x.x versions. Basically, it was created to accumulate the applicable product attributes in the database and merge them into a lightweight table.

Flat catalogs are expected to result in fewer database queries for every action by combining data and keeping it all together. However, in reality, this turned out to be a complicated procedure because of heavy dependencies. 

Thus, it doesn’t work anymore. This is why using flat catalogs is not the best practice for Magento 2 speed optimization. In fact, Magento 2.3.0 has recommended disabling this function altogether. This cautious warning can be found on their official website. 

How is it helpful, and how can it be done?

As per Magento, if you don’t halt the use of the flat catalog, you’ll have to experience performance degradation, slow running, and other critical issues. Since there are no alternatives to the flat catalog available, you’ll be left with no choice but to disable it completely. To disable this function, follow these steps:

  • Visit Stores and click on Settings
  • Click Configuration
  • From the left panel, choose Catalog and expand the Storefront section
  • And then, in the Use Flat Category and the Use Flat Catalog Product fields, set No
  • Click the Save Configs option

And you are done. 

  • Clean Database Logs

If your store has been running for a few years now, there’s a possibility that database logs would have grown hundreds of MBs along with uncountable data entries. This clutter can slow down the entire store and can create a shortage of space in case the disk is already full. For this specific reason, you must optimize the Magento MySQL database.

Unfortunately, Magento 2 doesn’t come with any fundamental cron job tasks to clear database logs. While the feature request is quite old, there’s no official statement from the team of Magento developers pertaining to this option automatically cleaning entries. Moreover, you won’t be able to find any adequate module either. This means you’ll have to go creative and do it on your own to speed up the Magento store. 

How is it done?

To begin the cleanup, you’ll require access to the PHPMyAdmin Panel in the hosting tools. You won’t find any basic way to reach the PHPMyAdmin Panel as it differs for every hosting. 

So, Magento developers generally recommend to clean the following list with logs:

  • dataflow_batch_export;
  • dataflow_batch_import;
  • log_customer;
  • log_quote;
  • log_summary;
  • log_summary_type;
  • log_url;
  • log_url_info;
  • log_visitor;
  • log_visitor_info;
  • log_visitor_online;
  • report_viewed_product_index;
  • report_compared_product_index;
  • report_event;
  • index_event.

Jotted down below is an example of an SQL query that lets you clean the logs and tables accordingly.

SET FOREIGN_KEY_CHECKS=0;TRUNCATE dataflow_batch_export;TRUNCATE dataflow_batch_import;TRUNCATE log_customer;TRUNCATE log_quote;TRUNCATE log_summary;TRUNCATE log_summary_type;TRUNCATE log_url;TRUNCATE log_url_info;TRUNCATE log_visitor;TRUNCATE log_visitor_info;TRUNCATE log_visitor_online;TRUNCATE report_viewed_product_index;TRUNCATE report_compared_product_index;TRUNCATE report_event;TRUNCATE index_event;SET FOREIGN_KEY_CHECKS=1;
  • Use ElasticSearch to Speed Up Search Results

In case your Magento store isn’t capable of storing, searching, processing, and analyzing huge volumes of data and returning answers quickly, it means the overall performance of your store could be slowing down. In such a scenario, ElasticSearch could be the ultimate solution.

How is it helpful?

You must note that ElasticSearch is mandatory for Magento 2.4 and above versions. Thus, if you’re using any version that is older than 2.4, consider installing the same. Also, switching to ElasticSearch will make it easier to upgrade to the latest 2.4 version of Magento.

How can you do it?

The correct installation process of ElasticSearch to older Magento versions will solely depend upon the setup you’re using. However, a few noteworthy points are here:

  • You must install ElasticSearch on a different host
  • Use clustering for adequate scalability and performance
  • You’ll require root privileges and extra software to complete the installation process

Once installed, turn ElasticSearch on in the Magento 2 Admin Panel. To do so, follow these steps:

  • Visit Stores and click Settings
  • Choose Configuration and click Catalog
  • Next, click Catalog Search

Here, look for Search Engine and switch to ElasticSearch. 

  • Arrange Your Indexers

Magento makes use of indexers to get quick access to data. For instance, to calculate some data each time, it can pull up data that has been already calculated from the indexers. This way, rather than consi



This post first appeared on Magento 2 Ecommerce, please read the originial post: here

Share the post

Magento 2 Speed Optimization | The Ultimate Guide

×

Subscribe to Magento 2 Ecommerce

Get updates delivered right to your inbox!

Thank you for your subscription

×