Why am I getting a jQuery is not defined error?

痴心易碎 提交于 2019-12-10 22:55:11

问题


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.


回答1:


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.




回答2:


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>



回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/4538994/why-am-i-getting-a-jquery-is-not-defined-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!