Search code examples
javascriptdojotwitter-bootstrap-3js-amd

How to use jQuery noConflict with Bootstrap and Dojo


I have written a widget that uses the latest version of jQuery, Bootstrap, and Dojo for AMD. The problem is it will be embedded in a page with an older version of jQuery. (client page, I can't control)

I'm trying to use jQuery's noConflict option, but I can't make it work when I try to load Bootstrap.

Simple noConflict works:

require(["jquery"], function (jQueryForPlugin) {

  // create local scope var and resets the global $ and jQuery 
  // to their previous values, so we don't mess up client's page
  var jQuery = jQueryForPlugin.noConflict(true);
  var $ = jQuery;

  // Now I can use $ like normal, and it will use my widget's jQuery version.
  $('.some-class').hide();

The problem is with other libraries, in particular Twitter Bootstrap, when I load them they don't see the new scoped jQuery variable.

Bootstrap can't see local noConflict $ and jQuery : JSFiddle of problem

require(["jquery"], function (jQueryForPlugin) {
  // Resets the global $ and jQuery to their previous values.
  var jQuery = jQueryForPlugin.noConflict(true);
  var $ = jQuery;

  require([ 'bootstrap'], function ( bootstrap) {
    // ERR: Bootstrap load throws error because it can't find 'jQuery' in its scope.

Solution

  • Vanilla Bootstrap isn't AMD-compatible. You'll have to edit Bootstrap's JS a bit to add in the AMD module boilerplate yourself, so that it can require() jQuery.

    See also https://github.com/twbs/bootstrap/pull/12909

    [ Edit: Bootstrap v3.2.0 should be AMD-compatible! See https://github.com/twbs/bootstrap/pull/13772 ]