Magento – How to stop calling paypal objects file on home page

javascriptmagento2payment-methodsrequirejs-config.js

We don’t want to make a call out to PayPal (https://www.paypalobjects.com/api/checkout.js) file when loading the homepage.
We should only be making calls to PayPal on the cart page and checkout.

Module Name: Magento_Paypal

File Path:
vendor/magento/module-paypal/view/frontend/requirejs-config.js

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

var config = {
    map: {
        '*': {
            orderReview: 'Magento_Paypal/order-review',
            paypalCheckout: 'Magento_Paypal/js/paypal-checkout'
        }
    },
    paths: {
        paypalInContextExpressCheckout: 'https://www.paypalobjects.com/api/checkout'
    },
    shim: {
        paypalInContextExpressCheckout: {
            exports: 'paypal'
        }
    }
};

Best Answer

You could try overwriting that Require JS file so it only loads on the pages you wish. * means load regardless of element, you can replace with a selector or selectors meaning the script will only load if those selectors are present.

This may work:

var config = {
    map: {
        '.checkout-index-index, .checkout-cart-index': {
            orderReview: 'Magento_Paypal/order-review',
            paypalCheckout: 'Magento_Paypal/js/paypal-checkout'
        }
    },
    paths: {
        paypalInContextExpressCheckout: 'https://www.paypalobjects.com/api/checkout'
    },
    shim: {
        paypalInContextExpressCheckout: {
            exports: 'paypal'
        }
    }
};

I say may because I haven't tried this with multiple selectors. If it doesn't support multiple selectors you could add it twice with a different selector each time.

Related Topic