Question

I did added JS file from design layout update from Admin CMS page- > Design layout update XML , but it showing jQuery is not defined error, When I view source , these files are being added before the requireJS file.
How to add JS from Admin->Content->Pages ->Open CMS page -> Design ->"layout update XML" ?

<head> 
 <script src="js/pi.googleMapStyles.js" order="100"/>
<script src="http://maps.google.com/maps/api/js?sensor=false" src_type="url" order="101"/>
<script src="js/jquery.gmap.min.js" order="102"/>
<script src="js/pi.global.js" order="103"/><script src="js/pi.init.map.js" order="104"/>
</head>

Thanks

Was it helpful?

Solution

You must quit what you have done so far in the XML layout.

You need requirejs-config.js in this path app/design/frontend/VendorName/Theme/ with bellow content:

var config = {
    map: {
        '*': {
            custom_js: 'VendorName_Theme/js/js_file_name'
        }
    },
    shim: {
        custom_js: {
            deps: ['jquery']
        },
    }
};


OR

You need requirejs-config.js in this path /app/design/frontend/VendorName/Theme/web/js/ with bellow content:

var config = {
    map: {
        '*': {
            custom_js: 'VendorName_ModuleName/js/js_file_name'
        }
    }
};

In a template you can call it:

<script>
    require([
        'jquery',
        'custom_js'
    ], function ($, script) {
        //Your code here
        //alert('Here');
    });
</script>


OR

In a template you can call it:

<script>
    require([
        'jquery',
        'VendorName_ModuleName/js/js_file_name'
    ], function ($, script) {
        //Your code here
        //alert('Here');
    });
</script>




You can add for any CMS Pages (from admin) a template file in Layout Update XML

<referenceContainer name="before.body.end">
    <block class="Magento\Framework\View\Element\Template" name="test" template="Magento_Theme::test.phtml"/>
</referenceContainer>

You can add for a test in test.phtml file from Magento_Theme in your current theme:

<pre>11111111</pre>
<script>
  require([
    'jquery',
    'Magento_Theme/js/js_file_name'
  ], function ($, script) {
    //Your code here
    alert('js_file_name - test');
  });
</script>


You can add for a test in js_file_name.js file from Magento_Theme in your current theme:

console.log(1234567890987654321);


After seeing your test work, you can change how you want it.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top