Search code examples
javascriptjquerybackbone.jsrequirejsunderscore.js

Why do I need to load jquery twice


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.


Solution

  • 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)