Skip to content
intermediate Phase 48 · Checkout Production

Checkout Performance

Lazy loading, async operations, caching, and JavaScript optimization for checkout

45m
0 problems
Topic Progress 0%

Lazy Loading Components

RequireJS Async Loading

// Lazy load checkout component
require([
    'Magento_Checkout/js/view/payment',
    'Magento_Checkout/js/model/payment-provider-list'
], function (paymentView, paymentList) {
    'use strict';

    // Payment methods loaded on demand
    paymentList.subscribe(function (methods) {
        methods.forEach(function (method) {
            require([method.component], function (Component) {
                // Component loaded asynchronously
            });
        });
    });
});

Checkout Step Lazy Loading

// Delay step initialization until needed
define([
    'jquery',
    'ko',
    'uiComponent'
], function ($, ko, Component) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'Vendor_Checkout/lazy-step'
        },

        initialize: function () {
            this._super();
            this.isInitialized = ko.observable(false);
            return this;
        },

        initStep: function () {
            if (!this.isInitialized()) {
                // Load heavy resources only when step is shown
                require(['Vendor_Checkout/js/heavy-resource'], function () {
                    this.isInitialized(true);
                }.bind(this));
            }
        }
    });
});

Component Preloading

<!-- Preload critical checkout components -->
<referenceBlock name="checkout.root">
    <arguments>
        <argument name="jsLayout" xsi:type="array">
            <item name="components" xsi:type="array">
                <item name="checkout" xsi:type="array">
                    <item name="children" xsi:type="array">
                        <item name="shipping" xsi:type="array">
                            <item name="component" xsi:type="string">Magento_Checkout/js/view/shipping</item>
                            <item name="deps" xsi:type="array">
                                <item name="0" xsi:type="string">Magento_Checkout/js/view/shipping-address-fieldset</item>
                            </item>
                        </item>
                    </item>
                </item>
            </item>
        </argument>
    </arguments>
</referenceBlock>

Async Operations

Parallel AJAX Requests

// Load shipping methods and payment methods in parallel
$.when(
    $.ajax({ "url": '/rest/V1/carts/mine/shipping-methods', "method": 'GET' }),
    $.ajax({ "url": '/rest/V1/carts/mine/payment-methods', "method": 'GET' })
).done(function (shippingResponse, paymentResponse) {
    var shippingMethods = shippingResponse[0];
    var paymentMethods = paymentResponse[0];

    // Both loaded simultaneously
    this.shippingMethods(shippingMethods);
    this.paymentMethods(paymentMethods);
}.bind(this));

Debounced Requests

// Debounce address lookup to prevent excessive API calls
var addressLookup = debounce(function (postcode) {
    $.ajax({
        url: '/rest/V1/directory/search',
        data: { "postcode": postcode },
        success: function (response) {
            // Process result
        }
    });
}, 300);

function debounce(func, wait) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            func.apply(context, args);
        }, wait);
    };
}

Promise-Based Checkout

// Modern async checkout flow
async function placeOrder(cartId) {
    try {
        // Sequential dependent operations
        await setAddress(cartId);
        await setShippingMethod(cartId);
        await setPaymentMethod(cartId);

        // Place order
        var orderId = await submitOrder(cartId);
        return orderId;
    } catch (error) {
        showError(error.message);
        throw error;
    }
}

Caching Strategies

Browser Caching

// Cache shipping rates in localStorage
var ShippingCache = {
    cacheKey: 'shipping_rates_',

    get: function (addressKey) {
        var cached = localStorage.getItem(this.cacheKey + addressKey);
        if (cached) {
            var data = JSON.parse(cached);
            if (Date.now() - data.timestamp < 300000) { // 5 min TTL
                return data.rates;
            }
        }
        return null;
    },

    set: function (addressKey, rates) {
        localStorage.setItem(this.cacheKey + addressKey, JSON.stringify({
            rates: rates,
            timestamp: Date.now()
        }));
    }
};

Server-Side Caching

// Cache checkout configuration
namespace Vendor\Checkout\Cache;

class CheckoutConfigCache
{
    public function __construct(
        private \Magento\Framework\Cache\FrontendInterface $cache
    ) {}

    public function getConfig(int $cartId): ?array
    {
        $cacheKey = 'checkout_config_' . $cartId;
        $cached = $this->cache->load($cacheKey);

        if ($cached) {
            return json_decode($cached, true);
        }

        return null;
    }

    public function saveConfig(int $cartId, array $config): void
    {
        $cacheKey = 'checkout_config_' . $cartId;
        $this->cache->save(
            json_encode($config),
            $cacheKey,
            ['checkout_config'],
            300 // 5 minutes
        );
    }
}

JavaScript Optimization

Bundle Optimization

<!-- Reduce checkout JS bundle size -->
<page layout="checkout">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Text" name="checkout.requirejs">
                <arguments>
                    <argument name="text" xsi:type="string"><![CDATA[
                        <script type="text/x-magento-init">
                        {
                            "*": {
                                "Magento_Ui/js/core/app": {
                                    "components": {
                                        "checkout": {
                                            "component": "Magento_Checkout/js/view/checkout",
                                            "deps": [
                                                "Magento_Checkout/js/view/shipping"
                                            ]
                                        }
                                    }
                                }
                            }
                        }
                        </script>
                    ]]></argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>

Minification and Compression

# Enable JS/CSS minification
php bin/magento config:set dev/js/minify_files 1
php bin/magento config:set dev/css/minify_files 1

# Enable static file signing
php bin/magento config:set dev/static/sign 1

# Deploy static content
php bin/magento setup:static-content:deploy -f

Performance Monitoring

// Track checkout performance metrics
var checkoutMetrics = {
    startTime: Date.now(),

    trackStep: function (stepName) {
        var elapsed = Date.now() - this.startTime;
        console.log('Step ' + stepName + ': ' + elapsed + 'ms');

        // Send to analytics
        if (window.ga) {
            ga('send', 'timing', 'checkout', stepName, elapsed);
        }
    }
};

Quiz

1. What is the benefit of lazy loading checkout components?

Question 1 options

2. How can you prevent excessive API calls during address entry?

Question 2 options

3. What does static file signing provide?

Question 3 options

Flashcards

Question

Lazy loading benefit?

Answer

Faster initial load by deferring component initialization

Question

Debouncing purpose?

Answer

Prevents excessive API calls during rapid user input

Question

Cache TTL purpose?

Answer

Expires cached data after specified time to ensure freshness

Question

Static file signing?

Answer

Appends version hash to URLs for cache busting

Revision Notes

Key Takeaways

  • 1. Lazy loading defers component initialization until needed
  • 2. Debouncing prevents excessive API calls during user input
  • 3. Browser caching stores shipping rates and checkout config locally
  • 4. Server-side caching reduces database queries for checkout config
  • 5. JS minification and static signing improve load times

Interview Tips

  • Discuss lazy loading strategies for checkout components
  • Explain debouncing vs throttling for API calls
  • Describe caching layers: browser, server, CDN

Cheat Sheet

Performance Optimization:
  Lazy load: defer component init
  Debounce: delay API calls
  Throttle: limit call frequency

Caching:
  Browser: localStorage for rates
  Server: cache frontend for config
  CDN: static files with signing

Optimization:
  JS minification
  CSS minification
  Static content deploy
  Bundle analysis