Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

javascript - How can I load jQuery if it is not already loaded?

I have a initializor.js that contains the following:

if(typeof jQuery=='undefined')
{
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = 'jquery.js';
    headTag.appendChild(jqTag);
}

I am then including that file somewhere on another page. The code checks if jQuery is loaded, and if it isn't, adds it to the Head tag.

However, jQuery is not initializing, because in my main document, I have a few events declared just to test this. I also tried writing some jQuery code below the check, and Firebug said:

"jQuery is undefined".

Is there a way to do this? Firebug shows the jquery inclusion tag within the head tag!

Also, can I dynamically add code into the $(document).ready() event? Or wouldn't it be necessary just to add some Click events to a few elements?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>). You would have to add an onload listener to the script (jqTag) to detect when it loads and then run your code.

e.g.

function myJQueryCode() {
    //Do stuff with jQuery
}

if(typeof jQuery=='undefined') {
    var headTag = document.getElementsByTagName("head")[0];
    var jqTag = document.createElement('script');
    jqTag.type = 'text/javascript';
    jqTag.src = 'jquery.js';
    jqTag.onload = myJQueryCode;
    headTag.appendChild(jqTag);
} else {
     myJQueryCode();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...