4

I'm asking this question as I'm unsure about the best way to proceed.

I've ported a module from Magento 1 to Magento 2, and it includes some Javascript tracking snippets that contain a small amount of dynamic data, e.g. an extra line or two if you've just added a product to your cart.

I'm concerned that the full page cache in Magento 2 will get in the way of the dynamic nature of some of these snippets.

Questions:

  1. Do I need to worry about the FPC here?
  2. Should I be using a UI component for this?
  3. Would this be the recommended approach for implementing these kinds of things in Magento 2?
5
+125

Do I need to worry about the FPC here?

Yes, if you are using dynamic contents.

Should I be using a UI component for this?

It depends. UI component is an extended version of knockout js MVVM pattern. The main purpose of UI component is to add updates to DOM elements. Have a look at

app/code/Magento/Checkout/view/frontend/templates/cart/minicart.phtml
app/code/Magento/Checkout/view/frontend/web/js/view/minicart.js
app/code/Magento/Checkout/view/frontend/web/template/minicart/content.html

If you do not want to add any updates to the DOM you do not need to use UI component.

Check how they have implemented GoogleTagManager without UI components.

app/code/Magento/GoogleTagManager/view/frontend/templates/js.phtml

Most of the data in the front end are observable. So if you want to track events like add to cart you can subscribe observable related object.

E.g

define([
    'Magento_Customer/js/customer-data'
], function (customerData) {
    'use strict';
    function initialize() {
        var cartData = customerData.get('cart');
        cartData.subscribe(function (updatedCart) {
            // do what ever with updated cart
        }, this);
    }

    document.observe('dom:loaded', function() {
        initialize();
    });
});

Would this be the recommended approach for implementing these kinds of things in Magento 2?

I think so. Have a look at the way Magento implemented the mini cart. They have stored data in local storage and bind to the DOM using observable. Check app/code/Magento/Customer/view/frontend/web/js/customer-data.js how they store, retrieve and update data from/to local storage.

There is a plugin that can be used to debug knockout js context. https://chrome.google.com/webstore/detail/knockoutjs-context-debugg/oddcpmchholgcjgjdnfjmildmlielhof

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.