I have same problem with owl carousel slider Js. sometime js load and sometime show error. So at that time i found many solutions. And at last i found solution which is works well. There are two ways to include Js from the template in Magento 2:
<script type="text/x-magento-init">
- data-mage-init attribute.
Either way can be used to pass data to the script within the json definition.
app/code/VendoreName/ModuleName/view/frontend
requirejs-config.js
var config = {
map: {
'*':{
owlcarousel:'VendoreName_ModuleName/js/owlcarousel',
reltaed_js:'VendoreName_ModuleName/js/reltaed_js',
}
},
shim:{
'owlcarousel':{
deps: ['jquery']
},
'reltaed_js':{
deps: ['jquery']
}
}
};
- For example, using the x-magento-init script tag, in the template you have:
<script type="text/x-magento-init">
{
"*": {
"VendoreName_ModuleName/js/reltaed_js": {
"slidername": "#you_id",
"slideritems": "4"
}
}
}
</script>
- For example, using the data-mage-init attribute into tag, in the template you have:
<div data-mage-init='{"reltaed_js": { "slidername": "Param1"}}'>
app/code/VendoreName/ModuleName/view/frontend/web/js
reltaed_js.js
define([
'jquery',
'domReady',
"owlcarousel",
], function ($,dom,owlCarousel) {
'use strict';
return function(config) {
$(config.slidername).owlCarousel({
items: config.slideritems,
margin: 10,
lazyLoad: true,
autoplayHoverPause: true,
autoplay: true,
nav: true,
dots:true,
loop:true,
slideSpeed: 300,
paginationSpeed: 400,
responsiveClass: true,
responsive: {
0: {
items: 1,
nav: true
},
480: {
items: 2,
nav: true
},
770: {
items: 3,
nav: true
},
1024: {
items: config.slideritems,
nav: true
}
}
});
}
});
Add owl js at app/code/VendoreName/ModuleName/view/frontend/web/js/owlcarousel.js
Rename owlcarousel.min.js to owlcarousel.js
Add Owl CSS into your layout like this
<head>
<css src="VendoreName_ModuleName::css/owl.carousel.min.css" />
<css src="VendoreName_ModuleName::css/owl.theme.default.css" />
</head>
Note: I recommend to use x-magento-init script tag
I Hope This Helps You