1

In my html page, I need to put jquery twice. If I take anyone of them out my page , then the page does not get rendered. Kindly note that both the included "jquery" are pointing to same location.

I am using backbone.js. I have added require.js to include jquery at the bottom of the page. Also, I need to add jquery at the start of the page. Once I add these two, then my whole page renders properly. If I take any of them out I start getting issues.

Can someone throw some light on why this issue is happening.

Script added in the HEAD tag of page:

 <script src="../vendors/jquery/dist/jquery.min.js"></script>

Script added in BODY bottom:

<script type="text/javascript">
require(['common'],function()
{
  require(['jquery', 'fastclick','nprogress','charts','underscore'],function()
  {
    require(['firstDashboardController']);
  });
});
</script>

If I take the jquery included at the top of the page below is the error I get:

enter image description here

If I take the jquery out of require module at the bottom, then below is the error:

enter image description here

P.S: I am using chart.js an external file to draw graph and stuff on the page.

3
  • are you including your script tags within the HEAD or BODY tags?
    – TetonDan
    Commented Jul 20, 2016 at 20:29
  • intital jquery in the head. the require one in the body at the bottom. Commented Jul 20, 2016 at 20:31
  • @TetonDan kindly help.. Commented Jul 20, 2016 at 21:34

2 Answers 2

1

A common solution to this problem would be to use jQuery's built-in $.noConflict(true) but I would suggest you to use the following in your bottom <script> tag code to prevent the double loading of jQuery altogether:

requirejs.config({
    paths: {
      jquery: '../vendors/jquery/dist/jquery.min.js'
    }
  });

  if (typeof jQuery === 'function') {
    //jQuery already loaded, just use that
    define('jquery', function() { return jQuery; });
  }

  require(["jquery"], function($) {
   //This $ should be from the first jquery tag, and no
   //double load.
  });

source: https://github.com/requirejs/requirejs/issues/535

Getting rid of one include won't work because:

  1. You need jQuery to be loaded before Bootstrap (1st <script> tag)
  2. The module's you also loaded using RequireJS can't directly use jQuery, that is loaded via a <script src="jQuery.min.js"> tag (bottom tag)
1
  • Worked Perfectly. Thank you so so much. Commented Jul 21, 2016 at 18:30
1

jQuery registers itself using the global functions "$" and "jQuery", even when used with RequireJS. If you want to turn off this behaviour you have to call noConflict function, you might need to

define('jquery-require', ['jquery'], function (jq) {
  return jq.noConflict(true);
});

require(['jquery-require'], function(jq) {
  console.log(jq);      // working
  console.log($);       // undefined
  console.log(jQuery);  // undefined
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.