How to optimize a Magento e-commerce page

The speed of your website has a significant impact on your visitors’ decision whether or not to stay and browse your store. Please bear in mind that TIME is MONEY. While your e-commerce page is slowly loading, your “potential customers” can even add thousands of items to their cart on your competitors’ sites. This blog will instruct both admins and developers on how to optimize a Magento e-commerce page.

Part 1: How Site Administrators Can Optimize a Magento E-commerce Page

Magento provides a useful and convenient admin panel to help administrators conquer their own e-commerce site. Let’s take its advantages and learn some tips to maximize your Magento system.

1. Enable flat category and flat product for the indexing process

Database loading significantly affects your page performance. As an admin, you can improve it by going to Stores → Configuration → Catalog → Catalog → Storefront,

→ Choose Yes in Use Flat Catalog Category and Use Flat Catalog Product. (the last 2 fields in the below image)

This way can speed up the request time for the database.

catalog-flat-test-category

2. Should not use bundling js

You should not turn on bundling js to optimize your Magento site because although it combines all assets present in the system and distributes them among same-sized bundles, the browser still loads ALL the JavaScript bundles, not just the ones needed.

So, go to Stores → Configuration → Advanced → Developer → JavaScript Settings, and choose No in Enable JavaScript Bundling.

3. Merge Magento JavaScript

One more way to faster Magento site is merging and minifying Magento JS and CSS.
– For merging process, it will automatically combine all separate JS and CSS files into some bigger files
– For minifying process, in other words, it will compress the CSS and JS files, minimize their sizes
By these ways, website will be improved better. Choose Yes in the below fields to allow using these functions.

Similarly, turn on field Merge JavaScript Files and Minify JavaScript Files above instructor in step 2.

merge-js-magento-2

4. Use cache to speed up

Cache is a wonderful tool to avoid generating almost everything from the beginning each time. As Cache can save some factors, so it will just take data for the next loading. Thus, it helps increase the page speed.

You should turn on a cache type available in System → Cache Management. Click Enable it and then submit to execute your requests.

5. Optimize your image

Image is an essential factor of any E-commerce system, even Magento. When you have a heavy image, you will cause bad performance both on uploading and loading process. To minimize it, try to compress your image with some common formats: .jpg, .png or .svg.

There are a number of pages allowing compressing images online, and it is also free. You can freely find them with keyword “compress image online” . This is for reference: https://tinypng.com/

6. Use Full page cache by Varnish

What you need to do is go to Stores > Configuration > Advanced > System > Full Page Cache, and choose Varnish Cache in the Caching Application field before completing Varnish configurations.

Because Magento strongly recommends using Varnish cache, it will help your site have a better user experience.

Part 2: How Magento Developers Can Optimize a Magento E-commerce Page

Magento platform is a huge, complex and difficult area for web developers, however, it also has a special attraction. The harder building a Magento site is, the more tremendous optimizing it is. Here, you can find some interesting tips to maximize your code and improve your coding skills significantly.

1. Follow Magento dev documents

Recently, there are a lot of websites providing Magento materials. Developers often prefer these instructions to the original Magento documents because of their easy readability and better comprehension.

However, it is a huge number of forums and blogs that the instructions somehow are not completely correct. The author, under an aspect of their experience, may publish some outdated or incorrect information.

Thus, to quickly reach the authentic Magento source, developers should follow the original Magento documents, available for all versions at this link.

2. Use Varnish cache instead of the others

Magento documents for cache configuration cited that “ Varnish cache is an open-source web application accelerator, also referred to as an HTTP accelerator or caching HTTP reverse proxy”.

Storing files in memory, it will reduce the response time and network bandwidth consumption on requests. Besides, Magento strongly recommend Varnish cache to users because it is designed to accelerate HTTP traffic

FYI, refer to this link for more reference.

Use Varnish cache instead of the others

3. Replace Magento’s constructor injection pattern with Proxy

Magento’s constructor injection pattern helps to flexibly manage class dependencies. However, constructor injection causes a chain reaction of object instantiation when you create an object. (The original object has dependencies that have dependencies, and those objects have dependencies, and so on.)” (Magento dev docs about Proxy pattern).

Thus, it will generate unnecessary performance impact. To solve it, developers should use proxies. Proxies extend other classes to become lazy-loaded versions of them. They have a lot of advantages:

(+) A real instance of the class a proxy extends is created only after one of the class’s methods is actually called.

(+) A proxy implements the same interface as the original class, so it can be used as a dependency anywhere the original class can.

(+) A proxy has only one dependency: the object manager.

(+) Proxies are generated codes which do not need to be manually written. Reference a class in the form \Original\Class\Name\Proxy, if the class does not exist, it will be generated.

See Referenc

4. Use Repository instead of Model

Repositories give service requestors the ability to perform, create, read, update, and delete (CRUD) operations on entities or a list of entities.

Your page speed can benefit a lot from Repository.

Developers are clearly separating business logic from the code that is responsible for storing such data. Hence, it helps create cleaner code which is easier to optimize and modify without influencing the rest and its dependencies.

Furthermore, you can avoid lazy-loading as you do not need to load one model several times. Repository in a request will gather and save models into an array.

Next time, you just need to load from the repository. As a result, you can avoid resource consumption.

See reference

5. Declare registry to use model anywhere

Magento registry stores data to memory which is specific to a particular request and for a duration of that request only. The Mage class is instantiated as a singleton object for every request and the instantiated Mage object remains in memory and is accessible in all classes until the request completes and the response is sent.

Please note that the Core registry is used to store global variables. You can store global variables via register()method and fetch value of variables via registry() method.

6. Use CollectionFactory instead of model→load()

As you know, model→load() is a function that helps to take the record.

If you use the model, you have to load it many times whenever you get data, which will affect the page performance.

Instead, you should use CollectionFactory. In some cases, it is undesirable to share an object with other parts of the request. Every part wants to add its own filters. Factories were introduced to solve this problem of the new Collection object. Thus, instead of injecting a Collection, a CollectionFactory is better.

7. Use →setPageSize() to limit number When using CollectionFactory

Many developers consider using ->getItem(), →getFirstItem() when they want to get the collection item without foreach.

However, it is not recommended that the system have to load all the Collection but just pick up the first item. It causes resource consumption.

To solve this problem, you can use setPageSize() to limit the number of loaded collection.

8. $collection→getSize() is better than count($collection)

This is another problem of several Magento developers. To check if the returned collection has any item or not, they often check if count($collection) > 0.

However, please notice that if you use count($collection), you have one more query to count the number of items in the collection. Once again, it causes resource consumption.

Therefore, you should use $collection→getSize() because with this function, counting query will be included, avoiding resource consumption

9. Enable profiler

Enable profiling helps to perform tasks such as analyzing performance, how long it takes to process these tasks.

If the profiler is enabled, developers may find it easier to think about what affect performance or slow speed; and the way to optimize needed functions

See reference

10. Use Less instead of CSS

Less is just CSS but added some more exciting things, which helps you simplify this Cascading Style Sheet language.

Less is a backward-compatible language extension for CSS. Here, you can assign a value of a property in a variable, as well as you can also gather some properties in a “function” and call easily.

Besides, Magento has tools to auto-convert file .less to file .css, so, using “less” in building this platform is extremely convenient.

11. Never use cacheable=“false”

Although some contents such as customer account or checkout are not cacheable, all blocks are assumed to be, by default. However, this can be circumvented in the layout XML by some settings the cacheable attribute of a block to be false.

Therefore, it is not recommended to use that way. If any block in the layout XML is marked cacheable=“false”, none of the pages is cached in Full Page Cache.

Note that using any cacheable=”false” inside the default.xml file will disable caching for all pages on the site.

12. Use httpContext to avoid saving cache, in case this situation happens with full page cache

Most caching servers and proxies use a URL as a key for cache records. However, Magento URLs are not unique enough to allow caching by URL only.

To make each cached URL totally unique, we use HTTP context variables. Context variables enable the Magento application to serve different content on the same URL.

For more reference, refer to part Configure page variations

13. Use flat structure

When your custom module has complex and huge data (saved in several joined tables), the flat structure should be used.

Because Magento uses EAV model (Entities – Attributes – Values), data of entities are separated into smaller parts. It is a flexible versatile data structure that enables users to change the number of properties without having to change the database schema.

However, its weak point is that it slows the performance, the system has to join data several times before loading it. Therefore, Magento applies the flat structure to join again all objects, properties, and their values into each entity table. Flat tables can be updated by indexing process, and data just be loaded from flat tables, making a totally better performance.