Adding a jQuery Library to Magento 2

Create requirejs-config.js Companyname\Modulename\view\frontend\requirejs-config.js add

var config = {
   map: {
       '*': {
           bannerslider: 'Companyname_Modulename/js/flexslider',
       }
   }
};

Your Js file in your module Companyname\Modulename\view\frontend\web\js\flexslider.js
You just add jquery lib using following syntax

<script type="text/javascript">
require(['jquery','bannerslider'],function($){
    $(window).load(function() {
        $('.flexslider-8').flexslider({
            animation: "fade",
            controlNav: "thumbnails",
            slideshowSpeed: 2000,
            minItems: 2,
            maxItems: 4
        });
    });
});
</script>

second example

<script type="text/javascript">
    require(['jquery'],function($){
        $(window).load(function() {
            alert('jquery working');
        });
    });
</script>

I quote the Magento Docs.

To build a dependency on the third-party plugin, specify a shim in the following configuration files:

In your requirejs-config.js:

var config = {
  "shim": {
     "3-rd-party-plugin": ["jquery"]
    }
  };

Then include your third party plugin code in your Theme or Module: "web/js/3-rd-party-plugin.js" like so:

!(function($){
  // plugin code
  // where $ == jQuery
})(jQuery);

This solution is favorable because you are including your plugin file without any kind of modification.Simply replace the js file when the plugin author updates or even use a cdn!


Best thing to do is use a Magento 2 Module or a Theme to include such plugins/libraries. It is the recommended way and the best practice.


Method 1 > THEME: If the javascript/jquery library is theme related (In order to change the look and feel of the system).

  • Place the custom component source file in one of the following location
    [theme_dir]/web/js/
  • Place your requirejs-config.js file in
    [theme_dir]

Method 2 > MODULE: If the javascript/jquery library is related to a particular business function or handles a Magento feature. It should go inside a module.

  • Place the custom component source file in one of the following location
    [module_dir]/view/frontend/web/js/

  • Place your requirejs-config.js file in
    [module_dir]/view/frontend/

Magento 2 strongly recommends not changing the source code of default Magento components and widgets. All customizations must be implemented in custom modules or themes.