dole
dole

Reputation: 433

Why am I getting a jQuery is not defined error?

I have to use an external js file in order to load jquery. The code from my js file is below:

 document.write('<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>');

    (function($) {
        $(document).ready(function() {
            alert('it works!!');
        });
    })(jQuery);

In the firefox firebug console I see this error: "jQuery is not defined" and I think it is because the jQuery library is loaded after the $ function from my js file.

Do you have any idea about how can I fix this? If I run the script from the firebug console everything works fine.

Upvotes: 2

Views: 4398

Answers (4)

tcooc
tcooc

Reputation: 21199

Loading scripts dynamically might help you. however, you're trying to load it while the page is loading, which would be a bit different from loading it when the page is loaded.

My suggestion is kind of a hack:

document.write('<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js" onload="loaded()" onreadystatechange="loadedIE()"></script>');

function loadedIE() { //for ie
    if(this.readyState == 4){loaded();}
};

function loaded() {
    $(document).ready(function() {
        alert('it works!!');
    });
};

I think the readystatechange listener should work (its an IE hack).

Upvotes: 1

Elzo Valugi
Elzo Valugi

Reputation: 27856

You are correct about jquery not being loaded at the time you call it. You'll have to write a function that will load the jQuery library and only later call your code. Alternatively you can delay your code execution, but this is not 100% full proof.

Update. Link to check if jQuery has been loaded useful for a callback call.

Upvotes: 2

Ned Batchelder
Ned Batchelder

Reputation: 375484

Why are you using document.write to pull in jQuery? Just put the <script> tag in the HTML directly.

Upvotes: 1

Quentin
Quentin

Reputation: 943108

The generated <script> element will appear after the current script element, and the code in it will not be executed until after the current <script> element's code has finished.

You need to load the library before you start the <script> that tries to use it.

Change to:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
    (function($) {
        $(document).ready(function() {
            alert('it works!!');
        });
    })(jQuery);
</script>

Upvotes: 5

Related Questions