I'm struggling to understand where and how to correctly configure RequireJS to load my custom JS and it's dependencies. What I have below is working but I don't think it's set up correctly.
My theme requirejs-config.js
var config = {
paths: {
'myapp': '"js/myapp"',
'owlcarousel': 'js/vendor/owl.carousel',
},
shim: {
'myapp': {
deps: ['jquery','owlcarousel']
},
'owlcarousel': {
deps: ['jquery']
},
}
};
My custom JS myapp.js
require(['jquery','owlcarousel'], function($){
var myCarousel = $(".carousel").owlCarousel();
console.dir($);
console.log(myCarousel);
});
To get myapp.js to output as expected, I have to put the following in one of my template files but if I load it just after the body tag it gives an error, which suggest that my script it not waiting for require resources before it runs and only works by chance if it's loads later.
<script>
require (['js/sozoapp'], function() {});
</script>
Can anyone explain what I'm missing here?
1 Answer 1
Can you plz change with above code,
var config = {
paths: {
'myapp': 'js/myapp',
'owlcarousel': 'js/vendor/owl.carousel',
},
shim: {
'owlcarousel': {
deps: ['jquery']
},
'myapp': {
deps: ['jquery','owlcarousel']
},
}
};
-
Thank you @Rakesh. After making your changes and moving the following code after the body tag it now works.
<script> require (['js/myapp'], function() {}); </script>But am right to include the code above after the body tag and should myapp.js also include?require(['jquery','owlcarousel']Paul Benbow– Paul Benbow2016年05月18日 07:35:04 +00:00Commented May 18, 2016 at 7:35 -
you can add anyplace your require js code in templateRakesh Jesadiya– Rakesh Jesadiya2016年05月18日 07:41:31 +00:00Commented May 18, 2016 at 7:41
-
its working at any place?Rakesh Jesadiya– Rakesh Jesadiya2016年05月18日 07:49:39 +00:00Commented May 18, 2016 at 7:49
-
Yes it works now when I add
<script> require (['js/myapp'], function() {}); </script>straight after the body tag. But do I need the following in myapp.jsrequire(['jquery','owlcarousel']?Paul Benbow– Paul Benbow2016年05月18日 09:44:23 +00:00Commented May 18, 2016 at 9:44 -
1@Ben-Space48 yes you're right, it does error without it in the 'owlcarousel' in myapp.js.Paul Benbow– Paul Benbow2016年05月25日 13:08:34 +00:00Commented May 25, 2016 at 13:08