Search code examples
jquerydjangotwitter-bootstrapbackbone.jsrequirejs

Bootstrap.js conflicts with require.js and disables Navbar dropdown


I am working on a Django site, so I have a base.html with all my common stuff and extend it to the pages I need

Common scripts that are used by the entire site are in my base.html:

<script src="/static/js/libs/jquery/jquery.js"></script>
<script src="/static/js/libs/jquery/jquery-ui-1.10.1.custom.min.js"></script>
<script src="/static/js/libs/bs3/bootstrap.min.js"></script>


My dashboard.html extends base.html , I am using require.js only for the dashboard.html and it includes the following at the very bottom:

<script data-main="/static/js/dashboard/main" src="/static/js/libs/require/require.js" type="application/javascript"></script>

My main.js

requirejs.config({
    paths: {
        'jquery': '../libs/jquery/jquery.min',

        // NOTE 1
        //'bootstrap': '../libs/bs3/bootstrap.min',

        // Backbone JS & Co
        "underscore": '../libs/underscore/underscore-min',
        "backbone": '../libs/backbone/backbone-min',

        // Dashboard Chart
        "salesView": 'views/Sales/DailySalesView',
    },
});

// Load Dashboard elements
require(["jquery", "underscore", "backbone", "salesView"], function ($, _, Backbone, SalesView) {

    // Show modal when dashboard page loads
    $('#loading-modal').modal('toggle');

}, function (err) {
    console.log(err)
});

NOTE 1:

When I have bootstrap ENABLED in my main.js, the modal loads fine, BUT the top Navbar dropdown ul.nav > li.dropdown stops working.

So I DISABLED bootstrap in my main.js, since bootstrap.js is already added in my base.html. Top Navbar dropdown works now BUT I get the following error

TypeError: $(...).modal is not a function


Q: Since bootstrap.js is already added in my base.html, I am assuming it's already loaded and the main.js should be having access to it. Why isn't it the case? How do I solve this ?

Any help/advice would be appreciated.

Thanks in Advance


Solution

  • You're loading jQuery with a script tag and loading it with RequireJS. This is a recipe for confusion. what happens is that Bootstrap is installed on the jQuery that is loaded with script but not on the one that RequireJS loads.

    One way to solve the problem is to remove jquery from your paths and instead add into your main.js a fake jquery module that just reuses the one loaded with script:

    define('jquery', function () {
        return $; // Just return the jQuery loaded with `script`.
    });
    

    Add it after your call to requirejs.config but before your require call.