Magento Tutorials Manually Load JS Component in Magento 2 (data-mage-init / magento-init)

« Back to Magento Tutorials

Magento 2 allows you to load JS components using JSON in script blocks with a type of text/x-magento-init or by specifying a data-mage-init parameter on any element. This is great and allows you to pass data directly into the JS object and it all works automatically.

Sometimes you may want to lazy load a JS component. An example of this would be you want to load a script after first checking the device type. Another example might be that you want to load a JS component after an AJAX callback. Either way, there's no clear way in the Magento 2 documentation that states how to do this but fortunately it's pretty easy.

require([
    'mage/apply/main'
], function(main) {
    main.applyFor(
        '*',                              // Element selector
        {testConfigValue: '123'},         // JSON string - config data
        'YourVendor_Module/js/component'  // Component name
    );
});

Let's look at the 3 parameters to the applyFor method.

Element Selector

The first parameter (*) is the element selector that the component is bound to. If this is set as '*' then the component won't be bound to an element and will be included right away. If you enter a CSS selector here, the component will only be loaded if the selector matches 1 or more elements. If the selector does not match any element then the component will not be loaded. If it matches more than 1 element, the component will be loaded once but executed against each element.

Config Data

The second parameter is a JSON string that represents the config data. If you don't want to pass any data, just include an empty JSON object ({}).

Component Name

The third parameter is the component name that you want to load. This value does not include the file extension (.js).

Create a Basic Component to Load Manually

Let's say we have a module called FishPig_MyModule that is installed at app/code/FishPig/MyModule. We manually load a component like this:

require([
    'mage/apply/main'
], function(main) {
    main.applyFor(
        '*',
        {fruitName: 'Apple'},
        'FishPig_MyModule/js/component'
    );
});

The above code will load the following JS file: app/code/FishPig/MyModule/view/frontend/web/js/component.js.

This file can be any Magento component but here is a quick/basic example of a JS file that takes the config and element passed.

define([
], function() {
    return function(config, element) {
        // Access the config option
        var fruitName = config.fruitName;

        // element will be null as we set '*' as element selector
        // If we set an element selector, element would be that element

        // We return a public object
        // You can add public methods and variables here
        return {};
    };
});