I'm working on a new Magento 2 installation with the Porto theme and have noticed that when you first visit the site or have the browser cache disabled you get a lot of of jQuery conflict errors. Below are examples of these errors from both the theme and core Magento2.
examples:
(index):394 Uncaught TypeError: $(...).swMegamenu is not a function
dataPost.js:13 Uncaught TypeError: $.widget is not a function
When I look how these jQuery functions are being initiated, I see it's using requireJs correctly to load jQuery.
<script type="text/javascript">
require([
'jquery',
'Smartwave_Megamenu/js/sw_megamenu'
], function ($) {
$(".sw-megamenu").swMegamenu();
});
</script>
AND
define([
"jquery",
"mage/template",
"jquery/ui"
], function($,mageTemplate){
$.widget('mage.dataPost', {......
I can fix it by adding var $ = jQuery.noConflict();
at the beginning of the function block (but this seems redundant as $
is already passed as a parameter to the function, it works though!)
Also, I can fix it by Merging all JS as suggested in answer to this question.
Merging the JS seems to be a good fix but I'd like to better understand why this is happening and the best approach to solving it.