markzzz
markzzz

Reputation: 47945

How to dynamically load a jquery library if not present?

I know, thanks to this tutorial, how to dynamically load jQuery (such as calling <script src="/widget/widget.js?type=normal" type="text/javascript"></script>) if the host website doesn't have it :

(function () {
    var jQuery;

    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");
        script_tag.setAttribute("src", pathWidget + "/scripts/jquery-1.7.min.js");

        if (script_tag.readyState) {
            script_tag.onreadystatechange = function () { // For old versions of IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    scriptLoadHandler();
                }
            };
        } else {
            script_tag.onload = scriptLoadHandler;
        }
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    } else {
        jQuery = window.jQuery;
        main();
    }

    function scriptLoadHandler() {
        jQuery = window.jQuery.noConflict(true);
        main();
    }

    function main() {
        jQuery(document).ready(function ($) {

        });
    }
})();

Well, now I'd like to do the same things for a jquery library. Let's says jQuery Cycle.

I've tried with :

var script_cycle = document.createElement('script');
script_cycle.setAttribute("type", "text/javascript");
script_cycle.setAttribute("src", pathWidget + "/scripts/jquery.cycle.all.js");

after :

script_tag.setAttribute("src", pathWidget + "/scripts/jquery-1.7.min.js");

but when I load the cycle into the document ready, I get this error :

$("#myRotator").cycle is not a function

Where am I wrong?

Upvotes: 0

Views: 1977

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

You can use $.getScript() for load external Javascript file.

if(!jQuery().cycle) {
    $.getScript('/scripts/jquery-1.7.min.js', 
    function() {});
}

Upvotes: 0

Bastian Rang
Bastian Rang

Reputation: 2187

try to check if the plugin is loaded:

if(!jQuery().cycle) {
  var script_cycle = document.createElement('script');
  script_cycle.setAttribute("type", "text/javascript");
  script_cycle.setAttribute("src", pathWidget + "/scripts/jquery.cycle.all.js");
  (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_cycle);
}

Upvotes: 1

Related Questions