3

Does anybody know a way to detect if the jQuery library was loaded and if not append it and start a script as a fallback solution after it's loaded to the DOM?

Here's my script:

if (typeof jQuery == 'undefined') {
    // if jQuery Library is not loaded
    var script = document.createElement( 'script' );
    script.type = 'text/javascript';
    script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
    document.body.appendChild(script);
    startScript();
} else {
    // cool, jQuery Library is loaded
    startScript();
}

function startScript() {
    $.noConflict();
    jQuery(document).ready(function($){
    .... // my jquery code
    });
}

Of course, above appends jQuery correctly but doesn't do anything because the script starts immidiately after appending. Any hint on this?

I appreciate any answer. Thanks!

1 Answer 1

4

You're fine except, as you said, that you can't call startScript immediately after appending the new script element. Instead, do a setTimeout loop:

// ...
document.body.appendChild(script);
maybeStart();

Where maybeStart looks like this (not within the body of the if, function declarations aren't valid there):

function maybeStart() {
    if (typeof jQuery === "undefined") {
        setTimeout(maybeStart, 100);
    }
    else {
        startScript();
    }
}

That checks if jQuery is loaded and, if not, waits a 10th of a second and checks again. When jQuery is found, it calls your startScript.

You might want to put a time limit in there (in case jQuery never loads, so you don't loop forever).

Alternately, you can hook a "load"-style event on the script element, but the mechanics of it vary from browser to browser. On some browsers it's just load as with, say, an img element; on IE (at least older versions), you have to use readystatechange, and on some versions of IE both work. So you have to keep a flag so you know whether you've fired off your script, etc., and...well, the above is less complicated in the case where you know the script creates a well-known global symbol (as is the case with jQuery).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.