繁体   English   中英

jQuery作为动态附加加载时的$(document).ready() <script>

[英]$(document).ready() when jQuery is loaded as a dynamically appended <script>

由于无法控制的原因,我必须通过动态附加的<script>标记加载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的时刻?

提前致谢

使用onloadonreadystatechange事件处理程序:

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
    });
}

您可以处理<script>元素的onreadystatechange事件,如果this.readyStatecomplete或已loaded ,请运行您的函数。
对于Firefox,请处理onload事件。

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

老式的答案:)您可以创建一个递归轮询功能,以检查$对象是否存在,例如:

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

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

并在加载jQuery脚本后立即运行poller函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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