Search code examples
jqueryajaxruntime-erroreventtrigger

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


I am trying to load jsvascript files at runtime like this

<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>

What I am trying here is to load jquery.colorbox.js before loading mbro.js, mbro.js just tries to initialize colorbox on click of a link. The content of the mbro.js is as follows

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

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

})(jQuery, window, document);

The HTML looks like this

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

But I am getting this error

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

What should be cause of this error and how to resolve this situation. Please give me some suggestions. Thank you in advance.


Solution

  • You should use $.getScript() jQuery method and keep async behaviour of ajax requests, e.g:

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

    To keep cache behaviour, you should use $.ajax method as mentionned in comment below. Here a workaround if for some reason you want to still use $.getScript method:

    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));