简体   繁体   中英

jQuery: trying to load jQuery dynamically. Not instantiating until after script has been run

javascript:var width=1900;
var height=800;

var jQueryScriptOutputted = false;
function initJQuery() {
    if (typeof(jQuery) == 'undefined') {
        if (! jQueryScriptOutputted) {
            jQueryScriptOutputted = true;
        var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript= document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
    oHead.appendChild( oScript);
        }
        setTimeout("initJQuery()", 50);
    } else {
        $(function() { 
        });
    }

}
initJQuery();



var container=$("#foreplay-root");
var canvas=$("#foreplay-root canvas");
canvas.width(width);
canvas.height(height);
container.width(width);
container.height(height);

the above is a bookmark (hence the javascript: at the beginning).

but, in the console, it says $ is undefined. But when I type $ or jQuery into the console (webkit of course) I get f unction (a,b){return new e.fn.init(a,b,h)} which is correct.

So, I'm thinking there is something wrong with the time it takes to init jQuery from teh time it loads.

*NOTE: this is for angry birds. http://chrome.angrybirds.com/

usually to everything that loads a file can be attached an event handler "onload"...

var jQueryLoaded = false;
function initJQuery() {
    if (typeof(jQuery) == 'undefined') {
        if (! jQueryScriptOutputted) {
            jQueryScriptOutputted = true;
        var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript= document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
    oScript.onload = function() {
       jQueryLoaded = true;
    }
    oHead.appendChild(oScript);
        }
        setTimeout("initJQuery()", 50);
    } else {
        while(!jQueryLoaded) {}
        $(function() { 
        });
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM