Problem with loading jQuery only in case of absence

I am using code from a blog which is very similar to the code in the answer to this SO question .

My problem is that the code puts jQuery on the list just fine, but for some reason the scripts after it don't recognize jQuery loading. What am I doing wrong?

I put the code in jsFiddle.

if (!window.loadjQueryOnce)
{
    function loadjQueryOnce(jQueryVersion)
    {
        jQueryVersion = typeof(jQueryVersion) != 'undefined' ? jQueryVersion : "1.7.2";

        if (typeof jQuery === "undefined") {
            var script_tag = document.createElement('script');
            script_tag.setAttribute("type","text/javascript");
            script_tag.setAttribute("src",
              "http://ajax.googleapis.com/ajax/libs/jquery/" + jQueryVersion + "/jquery.min.js")
            document.getElementsByTagName("head")[0].appendChild(script_tag);
        }
    }
}
+3
source share
3 answers

The problem is that you do not expect the script to execute before being called in HTML. See this example , which uses the code from the blog you mentioned. You need to put code that relies on jQuery in a function main.

+2
source

loadjQueryOnce('1.7.2') , jQuery, jQuery . http://jsfiddle.net/JfWeG/2/ , , , .

, jQuery JS , , , jQuery, jQuery script, .

// Load jQueryUI
if (!jQuery) loadjQueryOnce();
loadjQueryUI();

if (!jQuery) loadjQueryOnce();
loadjQueryDepedentScript();

, . , , .

, jQuery - , :

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        ...
    </head>
+1

. , .

<script type="text/javascript">
setTimeout(function() {
    if (typeof jQuery === "undefined") {
        alert('Not recognizing jQuery');
    }
}, 100);​
</script>

jsFiddle.

0

All Articles