How to use third-party Javascript Plugins in Magento 2

When we customize a Magento theme, we sometimes want to use third-party Javascript plugins. To add a JS library in Magento 2 is quite different from what we are used to doing in Magento 1. Magento 2 uses RequireJs library for nearly every JavaScript feature it has. Among other benefits, it improves the page loads by […]

By Yun Liu

When we customize a Magento theme, we sometimes want to use third-party Javascript plugins. To add a JS library in Magento 2 is quite different from what we are used to doing in Magento 1.

Magento 2 uses RequireJs library for nearly every JavaScript feature it has. Among other benefits, it improves the page loads by loading JS files asynchronously and only loading JS files the page needed. We should keep this in mind and avoid including the JS plugins in the head by <script src=”…”> tags when possible.  Moreover, for jQuery plugins which require jQuery to be loaded first, using <script src=”…”> tags won’t work. It will raise errors when the plugins attempt to use the global jQuery object. Because jQuery is loaded as a RequireJS module in Magento 2, the global “jQuery” object will not be defined until you use jQuery as a RequireJS module.

I’ll use the Owl Carousel jQuery plugin as an example to show you how to add third-party Javascript plugins in Magento 2 via RequireJS

First, download the Owl Carousel plugin.Unzip and copy the CSS files owl.carousel.min.css to the directory app/design/frontend/Your_Vendor /Your_Theme /web/CSS, and copy the js file owl.carousel.min.js to the directory app/design/frontend/Your_Vendor/Your_Theme /web/js.

Include the css files to your site in the app/design/frontend/Your_Vendor/Your_Theme /Magento_Theme/layout/default_head_blocks .xml:

<css src=”css/owl.carousel.min.css”/>

To include the JS file, you need to create a requirejs-config.js file under app/design/frontend/Your_Vendor/Your_Theme and set the path and dependencies for the plugin:

var
config = {
paths: {
'owlcarousel'
},
shim: {
'owlcarousel': {
'deps': ['jquery']
}
}
};

The “paths” configuration let you use a alias name “owlcarousel” for the JS file, and the “shim” configuration let you define the dependencies, jQeury in this case.

The file structure will be:

Now you can use it in a template. There’re two methods to call and initialize the carousel plugin:

Method 1 Imperative notation:

In your template where you want to use the carousel, you can call the library by

<
div
class="owl-carousel"
>
<
div
>
Your content
<
/
div
>
<
div
>
Your content
<
/
div
>
<
div
>
Your content
<
/
div
>
<
/
div
>

 

<
script
type="text/javascript"
>
requirejs(['jquery','owlcarousel'], function($, owl){
$('.selector-of-your-element').owlCarousel({
'option1': 'value1',
'option2': 'value2'
});
});

Please note here, the order of the dependencies’ names listed inside of requirejs([…] does not guarantee the files’ loading order, because RequireJS loads JS files asynchronously. That’s why it’s necessary to do the “shim” configuration in the requirejs-config.js in the previous step to make sure jQuery loads before the plugin.

Method 2 Declarative notation:

This method looks a little more complicated, but it helps to avoid generating Javascript directly with PHP so that we get cleaner code and better maintainability.

First you need to create a Javascript component app/design/frontend/Your_Vendor /Your_Theme/web/js/slider.js, with the follwoing code in it:

define([
'jquery',
'owlcarousel'
], function ($, owl) {
return
function(config, node) {
$(function () {
$(node).owlCarousel({
// choose the options you need
items: config.items,
slideBy: config.slideBy,
loop: config.loop,
dots: config.dots,
nav: config.nav,
autoplay: config.autoplay,
autoplayTimeout: config.autoplayTimeout,
autoplayHoverPause:
true,
rewind: config.rewind,
responsive: config.responsive
})
});
};
});

Then in your template, you can initiate this component by 2 ways:

1.Using the data-mage-init attribute:

<
div
class="owl-carousel"
>
"js/slider": {
"option1": "value1",
"option2": "value2"
}'>
<
div
>
Your content
<
/
div
>
<
div
>
Your content
<
/
div
>
<
div
>
Your content
<
/
div
>
<
/
div
>

2. Using the <script type=”text/x-magento-init” /> tag:

<
div
class="owl-carousel"
>
<
div
>
Your content
<
/
div
>
<
div
>
Your content
<
/
div
>
<
div
>
Your content
<
/
div
>
<
/
div
>

 

<
script
type="text/x-magento-init"
>
{
".selector-of-your-element": {
"js/slider": {
"option1": "value1",
"option2": "value2"
}
}
}
<
/
script
>

In both ways, you pass to the server the target DOM node and a JSON object with the JS component you want to use as the key and the options/values you want to configure as the value. Magento 2 will retrieve the information and pass them as arguments (config, node) to the JS component …/js/slider.js, and excute the code accordingly.

Now we know how to use the Owl Carousel in Magento 2, let’s try to use it for magento’s category product list widget:
Copy the file vendor/magento/module-catalog-widget/view/frontend/templates/product /widget/content/grid.phtml under app/design/frontend/Shero/pp-base/Magento_CatalogWidget/templates /product/widget/content . Let’s rename the template as

grid-slider.phtml so that we still have the option to use the original grid.phtml template.

Find this code ( line42) <ol class=”product-items <?php /* @escapeNotVerified */ echo $type; ?>”>. Edit it as:

<
ol
class="owl-carousel product-items < ?php /* @escapeNotVerified */ echo $type; ?>
data-mage-init='{"js/slider":{
"slideBy": "page",
"nav": "true",
"rewind": "true",
"dots": "false",
"responsive" : {"0" : {
"items": 1
},
"480" : {
"items": 2
},
"768" : {
"items": 4
}
}}'
>

 

Now we go to admin > Content > Blocks to create a new block, in this new block we insert category product list widget


After configuring the options and inserting the widget, the block content looks something like this


Change the template to our new one:

If you have a question about using third-party Javascript plugins on your Magento 2 project, feel free to comment here and we will respond right away.

Front End Developer