加载jQuery,等等

时间:2010-01-06 09:25:36

标签: javascript jquery load wait

我需要从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中真的很新,这真的让我很难过。任何人都可以让我朝着正确的方向前进吗?

2 个答案:

答案 0 :(得分:19)

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

function jqueryLoaded() {
    //do stuff
}

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

checkJquery();

答案 1 :(得分:1)

我很确定在加载所有脚本时应该触发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');
    }
}