Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Bootstrap scripts in environment that might have them already?

I would like to use popover (and its tooltip dependency) script from Bootstrap in my WordPress plugin.

It is likely that plugin will land in environments that already have Bootstrap and I am trying to determine how to implement this in robust way.

  1. I could try to check for plugin definitions and dynamically load scripts if they are not present (otherwise use what environment has). However timing seems challenging since one of scripts depends on another and having plugins of same name loaded doesn't guarantee it is compatible version or even Bootstrap script at all.

  2. Scripts seem to include noConflict() functionality, which I could try to use to stash away my own copies and ignore presence of global ones in any case. However again I am not sure how to get mechanics of this right, since popover needs tooltip to work. Also from looking through Bootstrap issue tracker later it seems that noConflict() in tooltips is currently broken and will be only fixed in v3. :(

  3. It seems like additional loader (such as yepnope) could deal with this for me, but it feels like digging myself deeper into a hole.

Which of these (or other than these) methods would be practical to implement?

like image 258
Rarst Avatar asked Jun 19 '13 15:06

Rarst


1 Answers

Use RequireJS to load in your own scripts and wrap them with some closure.

// let's say tooltip was defined already
$.fn.tooltip = function(data){
    $(this).mouseover(function(){
        console.log(data.title);
    });
};

// we'll apply the old tooltip to .tooltip1
$('.tooltip1').tooltip({
    title: 'tada',
    placement: 'bottom'
});

// what version of jquery did we have out here
console.log($.fn.jquery);

require({
    "paths": {
      "jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min",
      "bootstrap": "//twitter.github.io/bootstrap/assets/js/bootstrap.min"
    },
    shim: {
        "bootstrap": {
            deps: ['jquery'],
            exports: '$.fn.tooltip'
        }
    }
}, ['jquery', 'bootstrap'], function($){
    // what version of jquery do we have in here
    console.log($.fn.jquery);

    // now we apply the bootstrap tooltip to .tooltip2
    $('.tooltip2').tooltip({
        title: 'tada',
        placement: 'bottom'
    });
});

http://jsfiddle.net/moderndegree/prSUF/

like image 182
Brian Lewis Avatar answered Oct 03 '22 06:10

Brian Lewis