如何在可能已经拥有它们的环境中加载Bootstrap脚本?

Rar*_*rst 7 javascript twitter-bootstrap

我想在我的WordPress插件中使用Bootstrap的popover(及其tooltip依赖)脚本.

插件可能会在已经有Bootstrap的环境中着陆,我正在尝试确定如何以健壮的方式实现它.

  1. 我可以尝试检查插件定义并动态加载脚本(如果它们不存在)(否则使用什么环境).然而,时间似乎具有挑战性,因为其中一个脚本依赖于另一个并且加载了相同名称的插件并不能保证它兼容版本甚至Bootstrap脚本.

  2. 脚本似乎包含noConflict()功能,我可以尝试使用它来隐藏我自己的副本,并在任何情况下忽略全局副本的存在.然而,我不知道如何获得正确的机制,因为popover需要工具提示才能工作.此外,通过查看Bootstrap问题跟踪器,似乎noConflict()工具提示目前已被破坏,并且仅在v3中修复.:(

  3. 似乎额外的装载机(例如yepnope)可以为我处理这个问题,但感觉就像挖掘自己更深入一个洞.

哪些(或不是这些)方法可以实现?

Bri*_*wis 1

使用 RequireJS 加载您自己的脚本并用一些闭包包装它们。

// 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'
    });
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/modern Degree/prSUF/