加载jQuery,等等 [英] Load jQuery, wait

查看:85
本文介绍了加载jQuery,等等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to dynamically load jQuery and jQuery UI from a javascript, then check if it has loaded and do something afterwards.

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

I have done some research and found that I need to either use a callback or a settimeout. Trouble is I'm really new in javascript and it's really giving me a hard time. Can anyone set me in the right direction please?

推荐答案

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

I've never had to do this myself, but presumably you could just use a repeating timeout to check for presence of the needed objects:

function jqueryLoaded() {
    //do stuff
}

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

checkJquery();

这篇关于加载jQuery,等等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆