加载jQuery,等等

我需要从javascript动态加载jQuery和jQuery UI,然后检查它是否已加载并在之后执行某些操作。

function loadjscssfile(filename, filetype){ if (filetype=="js"){ //if filename is a external JavaScript file var fileref=document.createElement('script'); fileref.setAttribute("type","text/javascript"); fileref.setAttribute("src", filename); } else if (filetype=="css"){ //if filename is an external CSS file var fileref=document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", filename); } if (typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref); } loadjscssfile("http://localhost/js/jquery-1.3.2.min.js", "js"); loadjscssfile("http://localhost/js/jquery-ui-1.7.2.custom.min.js", "js"); 

我做了一些研究,发现我需要使用回调或settimeout。 麻烦的是我在javascript中真的很新,这真的让我很难过。 谁能让我朝着正确的方向前进?

我自己从来没有这样做过,但大概你可以使用重复超时来检查是否存在所需的对象:

 function jqueryLoaded() { //do stuff } function checkJquery() { if (window.jQuery && jQuery.ui) { jqueryLoaded(); } else { window.setTimeout(checkJquery, 100); } } checkJquery(); 

我很确定window.onload()函数应该在加载所有脚本时触发。 而且你不需要将东西绑定到jQuery中的’ ready ‘事件。

 loadjscssfile("http://localhost/js/jquery-1.3.2.min.js", "js"); loadjscssfile("http://localhost/js/jquery-ui-1.7.2.custom.min.js", "js"); window.onload = function() { if(window.jQuery && jQuery.ui) { alert('loaded'); } }