jQuery 在调用插件函数之前无法使用 ajax 加载插件文件,因此,给出了一种奇怪的结果

jQuery cannot load plugin file using ajax before calling the plugin function, thus, gives kind of weird result

我正在尝试像这样在运行时加载 jsvascript 文件

<script type="text/javascript" src="jquery/jquery.js"></script>
<script type="text/javascript">
var SRC_URL = 'http://localhost/mytest/scripts/';
var scripts = [
    'jquery/colorbox/jquery.colorbox.js',
    'app/mbro.js'
];

for (var x = 0; x < scripts.length; x++) {
    sUrl = SRC_URL + scripts[x];
    $.ajax({
        url: sUrl,
        dataType: "script",
        async: false,
        success: function() {
            console.log(x + ': ' + sUrl);
        }
    });
}
</script>

我在这里尝试的是在加载 mbro.js 之前加载 jquery.colorbox.jsmbro.js 只是尝试在单击 link 时初始化颜色框。 mbro.js内容如下

(function ($, W, D) {
    var abc = {};
    abc.UTIL = {
        openPopup: function () {
            $(".mbro").colorbox({
                inline: false,
            });
        },
    };

    $(D).ready(function ($) {
        abc.UTIL.openPopup();
    });

})(jQuery, window, document);

HTML 看起来像这样

<a class="mbro" href="media/popup">Browse</a>

但是我收到这个错误

TypeError: $(...).colorbox is not a function
$(".mbro").colorbox({

导致此错误的原因以及解决方法。请给我一些建议。提前谢谢你。

提前发送加载请求并不能保证一定会提前加载。在您的情况下,最好的做法似乎是在 colorbox.js 加载的 success 回调中加载 mbro.js。这样,您可以保证仅在 colorbox.js 加载完成后才加载您的脚本。

$.ajax({
    url: SRC_URL + 'jquery/colorbox/jquery.colorbox.js',
    dataType: "script",
    success: function() {
        $.ajax({
            url: SRC_URL + 'app/mbro.js',
            dataType: "script",
            async: false,
            success: function() {
                console.log('Done! Both loaded in the desired order!')
            }
        });
    }
});

编辑:

我没注意到这里使用了async: false。尽管如此,强烈不建议使用它,并且在 jQuery.

的最新版本中已弃用它。

您应该使用 $.getScript() jQuery 方法并保持 ajax 请求的异步行为,例如:

(function loadScript(x) {
    sUrl = SRC_URL + scripts[x];
    $.getScript(sUrl, function(){
        if(scripts[++x]) loadScript(x);
    });
}(0));

要保持​​缓存行为,您应该使用下面评论中提到的 $.ajax 方法。 如果出于某种原因您仍想使用 $.getScript 方法,这里有一个解决方法:

By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup()

var cacheSetting = $.ajaxSetup()['cache'];
$.ajaxSetup({
  cache: true
});
(function loadScript(x) {
    sUrl = SRC_URL + scripts[x];
    $.getScript(sUrl, function () {
        if (scripts[++x]) loadScript(x);
        else {
            $.ajaxSetup({
                cache: cacheSetting 
            });     
        }       
    });
}(0));