11

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.

4
  • You can directly call js inside layout xml head tag and you got js in each page. Dec 6 '16 at 9:26
  • Thank you for your answer. But if I would like to use require-config and load files with it, not like in Magento 1?
    – Anitr
    Dec 6 '16 at 10:05
  • Its also support in magento 2 you can check module-theme folder layout/default_head_block.xml file Dec 6 '16 at 10:07
  • Yes, i know. But, I want to use require-config.js the correct way.
    – Anitr
    Dec 6 '16 at 10:51
18

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

5
  • I call my script on \app\design\frontend\Enim\blank\Magento_CatalogWidget\templates\product\widget\content\grid.phtml, but I have requirejs-config.js and script in Theme folder (app/design/frontend/Vendor/Theme/requirejs-config.js). Is this ok? The problem is that I call my script from multiple different places.
    – Anitr
    Dec 7 '16 at 7:34
  • Your script only affects when the template templa‌​tes\product\widget\c‌​ontent\grid.phtml is called. Dec 7 '16 at 7:48
  • Yes, that's ok - the problem is with that one: magento.stackexchange.com/questions/149019/…, I am wondering if this issue is somehow connected to requirejs call.
    – Anitr
    Dec 7 '16 at 7:54
  • @KhoaTruongDinh I am a little confused by this. I haven't properly tested yet, but am I right in thinking that the function in custom_js.phtml is treated as a regular callback, performed after execution of the code contained within customscript.js? Or would I need to execute the code declared in customscript.js from within the function in custom_js.phtml? May 14 '18 at 12:46
  • 1
    @KhoaTruongDinh I'm also wondering why Iveta's answer states that your after.body.start should be changed to before.body.end? May 14 '18 at 12:47
7

Requirejs-config file: app/code/Vendor/Module/view/frontend/requirejs-config.js

var config = {
    paths: {            
         'myfile': "Vendor_Modulename/js/myfile"
      },   
    shim: {
    'myfile': {
        deps: ['jquery']
    }
  }
} 

Your js file should be in: app/code/Vendor/Module/view/frontend/web/js/myfile.js

Now you can use anywhere in your template file by calling the below method:

<script>
 require(["jquery","myfile"],function($,myfile){
     $(document).ready(function(){
        //call your js here...
     })
 })
</script>
6
  • Yes, that's correct. But I asked if anyone knows how to use it in Theme folder, not depending on Module - it should be loaded across the page, not only on one module.
    – Anitr
    Dec 6 '16 at 11:06
  • you can use it in theme folder as well, just call above script and you can use your js Dec 6 '16 at 11:09
  • please let me know if you have any issue Dec 6 '16 at 11:21
  • It works, thanks. But still, I am having issues on some other thing: magento.stackexchange.com/questions/149019/…
    – Anitr
    Dec 6 '16 at 14:02
  • Hi, Please let me know where to place1st step file?
    – Priya
    Apr 25 '19 at 6:44
5

There is a easier version using deps. Dependencies in the requirejs-config.js will load your file when loading requirejs itself (everywhere in the shop). Here is an example of how your requirejs-config.js should look:

var config = {
    // When load 'requirejs' always load the following files also
    deps: [
        'common-js'
    ],

    // Library file path.
    paths: {
        'common-js': 'js/Your-File-Name'
    },

    // The rest of your config file ...
1
  • This is the best solution by far. Clean, concise and great for external resources!
    – VIDesignz
    Feb 12 at 21:34
1

As an alternative approach to Khoa's recommendation, which is excellent Magento dev practice, you can paste your JavaScript in a .phtml file like this:

<srcipt>
require(["jquery"],function($){
 $(document).ready(function(){
    your script here...
 })
});
</script>

Then link your phtml file from default.xml as described in Khoa's answer, though I would recommend to add it to before.body.end. And, then call your JS script from within copyright.phtml, like this:

<script>
jQuery(document).ready(function($) {
..call your script here ..
});
</script>

copyright.phtml gets loaded on every page, even on pages like checkout, where the footer is omitted.

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.