Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript $(document).ready()当jQuery作为动态附加的文件加载时<;脚本>;_Javascript_Jquery - Fatal编程技术网

Javascript $(document).ready()当jQuery作为动态附加的文件加载时<;脚本>;

Javascript $(document).ready()当jQuery作为动态附加的文件加载时<;脚本>;,javascript,jquery,Javascript,Jquery,出于我无法控制的原因,我必须通过动态附加的标记加载jQuery,并且只能在某些任意事件时执行此操作,而不是在页面加载时 我的问题在于检测jquery准备就绪的时刻,因为下面的代码不起作用: (function(){ var s=document.createElement('script'); s.setAttribute('type','text/javascript'); s.setAttribute('src','http://ajax.googleapis.com

出于我无法控制的原因,我必须通过动态附加的
标记加载jQuery,并且只能在某些任意事件时执行此操作,而不是在页面加载时

我的问题在于检测jquery准备就绪的时刻,因为下面的代码不起作用:

(function(){
    var s=document.createElement('script');
    s.setAttribute('type','text/javascript');
    s.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js');
    document.getElementsByTagName('head')[0].appendChild(s);
})()

$(document).ready(function() {
  // something that uses jquery and currently doesn't work
});
我如何检测jquery准备在这个特定配置中使用的时刻

提前感谢

您可以处理
元素的
onreadystatechange
事件,如果
此.readyState
完成
加载
,请运行您的函数。
对于Firefox,处理
onload
事件

您可以在包装器函数中公开它,包装器函数将函数作为参数,并在jQuery已加载时调用它,或者在未加载时将其放入数组(以调用加载处理程序)。

老派答案:) 您可以创建一个递归轮询函数,检查$object是否存在,例如:

function poller(){
    if($.length != 0){
       //do what you want

    }else{
       setTimeout(poller, 100);
    }    
}

加载jQuery脚本后,立即运行轮询器函数。

使用
onload
onreadystatechange
事件处理程序:

var scr   = document.createElement('script'),
    head      = document.getElementsByTagName('head')[0];

scr.onload = scr.onreadystatechange = function(){
        if( scr.readyState ){
            if(scr.readyState === 'complete' || scr.readyState === 'loaded'){
                scr.onreadystatechange = null;                                                  
                myReadyFunc();
            }
        } 
        else{                               
                myReadyFunc();          
        }
};  

head.insertBefore(scr, head.firstChild);

function myReadyFunc() {
    $(document).ready(function() {
      // something that uses jquery and currently doesn't work
    });
}

js fila是否始终动态加载?可能重复。检查以下问题:-动态加载javascript文件的方式如何?