How to do Magento 2 performance optimization ?

Magento 2 is a pretty complex application. If you did not configure it correctly you will find it very slow. To do performance optimization, I am adding some pointers here as follows.

  1. Image optimization and lazy loading
  2. JavaScript optimization
  3. Font Optimization
  4. CSS optimization
  5. Caching techniques
  6. Server optimization
  7. Latest version of everything
  8. Light Weight theme
  9. Production mode
  10. Database optimization
  11. Code optimization
  12. Disable non required module
  13. Latest protocol http2
  14. Using Facade pattern for chat loader
  15. Serving static data from non cookie domain

Magento 2 checklist

Functional Components are to be validated before making it live, Please comment on things I missed to create a global list.

  1. Search results
  2. Minicart
  3. Banner/Sliders
  4. Contact form/forms
  5. Customer account create/Login/Logout
  6. Filters
  7. Megamenu
  8. Paginations
  9. add to cart/add to wishlist
  10. emails
  11. shipping method
  12. payment methods
  13. Tax
  14. product listing
  15. reviews display and posting
  16. indexing status and working
  17. Admin login/logout/creation
  18. place order
  19. captchas if enabled
  20. sale rules/discount configured
  21. pages/blocks/widgets –> creation/updation/deletion
  22. sitemap
  23. index.php/.htaccess configuration for multi-website
  24. newsletter
  25. cron configurations
  26. SEO/pixels
  27. third party modules functionality
  28. Reporting
  29. Speed page insight

Image Optimization For best performance in Magento 2

In webpages, Most of the bandwidth is taken by images and it affects webpage performance drastically. So, Image optimization becomes important for the best performance. I will not turn the wheel again. I will add the most important information here only.

Lazy/Preload loading for image optimization

Concept: You can take a look at it here.
Solution: You can use a free extension from mageplaza here.
Documentation: Documentation of extension can be found here

Layout shift for image optimization

Concept: You can take a look at it here.
Solution: The solution is itself in the above link. You can add height and width for images.

Image compression/Image format/Image size

Concept: Always use images with good compression and the size of images should be as per requirement.
Solution: Optimizer, Converter

Sprite Images for image optimization

Concept: This concept is used when there is a no of small images. we combine them in one image to reduce no of requests on the server.
Solution: you can find a good tool to create CSS sprite images here

Responsive images for image optimization

Concept: You can take look at it here
Solution: The solution is itself in the above link. You can add height and width for images.

You can find more information for speed optimization here

For custom requests, you can contact me here

Install composer 1.10 using php composer

Copy and paste this in terminal and hit enter. Composer version 1.10.23 will be installed in local directory. you can use it as php composer.phar install

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === '906a84df04cea2aa72f40b5f787e49f22d4c2f19492ac310e8cba5b96ac8b64115ac402c8cd292b8a03482574915d1a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php --version=1.10.23
php -r "unlink('composer-setup.php');"

Magento 2 backup script for developer

Magento 2 developer usually require taking backup of live environment and setup on local or creating staging environment. We need to take backup of Database, App folder and composer.json minimal. We can add media and other assets for full fledged setup. I created a simple script to create backup of these two folder after reading env.php file. It will decrease time to take backup. We just need to put these script at root and run it. It is very flexible and you can make changes to your requirement as well. I will keep updating it and will add new features.

<?php 
//create backup file
$envData = include('app/etc/env.php');

//taking database backup
echo "Taking database backup \n";
if(isset($envData['db'])){
    $mysqlDump = 'mysqldump --user='.$envData['db']['connection']['default']['username'].' --password='.$envData['db']['connection']['default']['password'].' --host='.$envData['db']['connection']['default']['host'] .' '.$envData['db']['connection']['default']['dbname'] .' > db.sql;'; 
    exec($mysqlDump);
}

//zipping files
echo "Zipping required files to setup environment \n";
exec('zip -r files.zip db.sql composer.json app/');

die('finished');
?>

Magento 2.x – Cannot process definition to array for type tinytext

I faced issue while setup:upgrade in magento 2 instance. I fixed this issue in three steps as below.

Step 1: I open this file : /vendor/magento/framework/Setup/Declaration/Schema/Db/DefinitionAggregator.php

Find this function and replace code:

   public function fromDefinition(array $data)
    {
        $type = $data['type'];
        if (!isset($this->definitionProcessors[$type])) {
            echo "<pre>"; print_r($data); exit();
            throw new \InvalidArgumentException(
                sprintf("Cannot process definition to array for type %s", $type)
            );
        }
        $definitionProcessor = $this->definitionProcessors[$type];
        return $definitionProcessor->fromDefinition($data);
    }

Step 2 : Run setup upgrade and you will find out column name and it’s details. Now login in to mysql console and replace invoiceNumber by column which we found in last step. You will get all table information.

SELECT table_name, column_name from information_schema.columns WHERE column_name LIKE '%invoiceNumber%';

Step 3: Now update that column using below command. Run again setup:upgrade

ALTER TABLE TableName MODIFY InvoiceNumber VARCHAR(250);

Remove magento 2 redundant modules

Magento 2 has added lot of new module and feature as compared to magento1x. It has some hidden dependencies. so, it slowdown magento 2 store. It is most common list of modules which generally do not required. You can add and remove module as per your requirement. You just need to add these modules in composer.json file and then run composer update.

"replace": {
        "magento/module-authorizenet": "*",
        "magento/module-google-adwords": "*",
        "magento/module-send-friend": "*",
        "magento/module-signifyd": "*",
        "magento/module-bundle-graph-ql": "*",
        "magento/module-catalog-graph-ql": "*",
        "magento/module-catalog-inventory-graph-ql": "*",
        "magento/module-catalog-url-rewrite-graph-ql": "*",
        "magento/module-cms-graph-ql": "*",
        "magento/module-cms-url-rewrite-graph-ql": "*",
        "magento/module-inventory-graph-ql": "*",
        "magento/module-configurable-product-graph-ql": "*",
        "magento/module-customer-graph-ql": "*",
        "magento/module-downloadable-graph-ql": "*",
        "magento/module-eav-graph-ql": "*",
        "magento/module-graph-ql": "*",
        "magento/module-grouped-product-graph-ql": "*",
        "magento/module-quote-graph-ql": "*",
        "magento/module-store-graph-ql": "*",
        "magento/module-swatches-graph-ql": "*",
        "magento/module-tax-graph-ql": "*",
        "magento/module-url-rewrite-graph-ql": "*",
        "magento/module-weee-graph-ql": "*",
        "temando/module-shipping-m2": "*",
        "dotmailer/dotmailer-magento2-extension": "*",
        "klarna/module-kp": "*",
        "klarna/module-ordermanagement": "*",
        "klarna/module-core": "*",
        "amzn/amazon-pay-sdk-php": "*",
        "amzn/amazon-pay-and-login-with-amazon-core-module": "*",
        "amzn/login-with-amazon-module": "*",
        "amzn/amazon-pay-module": "*",
        "vertex/module-tax": "*",
        "vertex/sdk": "*",
        "yotpo/magento2-module-yotpo-reviews": "*"
    },

Font optimization an avoid invisible text

Every Magento 2 store needs fonts to display styled text. Like other static assets it use bandwidth. It affects performance, if do not download before text required it. I am adding few suggestions for font optimization and some resources links as well. I will keep updated information for font here

  1. Try to use google font (why? read this link)
  2. Use no more than two fonts and check their size as well.
  3. Load them on priority basis using preload and swap to avoid invisible text during font loading (check this link)
  4. Use proper caching for fonts (check this link)
  5. Use less variants of fonts

You can check complete speed optimization guide Magento 2 speed optimization