Magento – Use require-config.js to load files needed on all pages

javascriptmagento2requirejs

I know how to use require-config.js in custom theme, but I would like to use custom javascript file (myfile.js) on all pages. In which directory should I add require-config.js and how to use it, so that it will work as it should?

Please, don't reference to Magento Official page.

Best Answer

requirejs-config.js uses for creating the JavaScript resources mapping. We can find all require configs under: pub/static/_requirejs.

As far as I know, the correct way to load our custom script via Require Js: using template to call our script. We will create new template with Magento\Framework\View\Element\Template its block class.

If we want to load js files on all pages and don't want to create a new module, our block should reference to before.body.end or after.body.start container in default.xml - Magento Theme module.

enter image description here

app/design/frontend/Vendor/Theme/Magento_Theme/layout/default.xml

<?xml version="1.0"?>

<page layout="3columns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <referenceContainer name="after.body.start">
        <block class="Magento\Framework\View\Element\Template" name="custom.js" template="Magento_Theme::custom_js.phtml"/>
    </referenceContainer>

</page>

app/design/frontend/Vendor/Theme/requirejs-config.js

var config = {
    map: {
        '*': {
            customScript:'Magento_Theme/js/customscript'
        }
    }
};

app/design/frontend/Vendor/Theme/Magento_Theme/web/js/customscript.js

define('jquery', function($) {

    //Your code here
    //alert('Here');

    }(jQuery)
);

Our template will call our script: app/design/frontend/Vendor/Theme/Magento_Theme/templates/custom_js.phtml

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

Clear Magento Cache and run static content deploy: php bin/magento setup:static-content:deploy

Related Topic