Magento 2 – Adding a jQuery Library

javascriptjquerymagento2

How can a third party developer add a jQuery library to Magento 2?

While Magento 2 includes a version of jQuery in their frontend themes, the jQuery object is not immediately available in the global namespace. I belive this is because Magento 2 uses RequireJS to pull in jQuery, and RequireJS won't load a module file until its needed.

This presents a problem for jQuery plugins. Normally, I'd include a plugin with HTML that looked something like this

<script type="text/javascript" src="http://magento-1-9-2-2.dev/js/commercebug/jquery-ui-1.8.custom/js/jquery.cookie.js"></script>

This, however, is not possible with Magento 2. Because the jquery.cookie.js file defines the jQuery plugin by using the global jQuery object, it will fail in Magento 2 with a jQuery is not defined error.

How should a front end developer include a standard jquery plugin library in Magento 2's front end application?

Best Answer

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>
Related Topic