如何在可能已经有引导脚本的环境中加载引导脚本

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

本文关键字:脚本 环境 加载      更新时间:2023-09-26

我想在我的WordPress插件中使用Bootstrap的弹出窗口(及其工具提示依赖)脚本。

插件很可能会在已经有Bootstrap的环境中着陆,我正试图确定如何以稳健的方式实现这一点。

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

  2. 脚本似乎包括noConflict()功能,我可以尝试使用它来隐藏我自己的副本,并在任何情况下忽略全局副本的存在。然而,我不确定如何得到这个机制的权利,因为弹出窗口需要工具提示工作。另外,从Bootstrap问题跟踪器来看,工具提示中的noConflict()目前已经损坏,只会在v3中修复。(

  3. 似乎额外的加载程序(如yepnope)可以为我处理这个问题,但感觉就像把自己挖得更深。

这些(或其他)方法中的哪一个是实际实现的?

使用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'
    });
});
http://jsfiddle.net/moderndegree/prSUF/