繁体   English   中英

从异步加载的外部脚本中使用jQuery插件

[英]Use jQuery plugin from asynchronously loaded external script

我有一个非常基本的jQuery插件,我将其加载到我的网页中,如下所示:

(function() {
    var tk = document.createElement('script');
    tk.src = '//www.test.com/scripts/jq_plugin.js';
    tk.type = 'text/javascript';
    tk.async = 'true';
    tk.onload = tk.onreadystatechange = function() {
        var rs = this.readyState;
        if (rs && rs != 'complete' && rs != 'loaded') return;
    };
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(tk, s);
})();

然后,我这样调用插件:

$(function(){
    $('#test').jq_plugin();
});

但是,当页面加载时,出现此错误:

Uncaught TypeError: undefined is not a function
(anonymous function)

我了解原因-在加载脚本之前会调用插件。 我知道一个快速而肮脏的技巧只是在插件调用周围使用setTimeout() ,但我不想这样做。 我尝试在jQuery之前和之后插入脚本,但得到相同的结果。

没有超时怎么办?

这是该插件的精简版本:

(function ( $ ) {
    $.fn.jq_plugin = function(options){
        return this.each(function() {
            return $(this).click(onClick);
            function onClick(e){
                console.log('ID: '+$(this).attr('id'));
            }           
        });
    };
}( jQuery ));

您创建了onload / onreadystatechange,但是它所做的只是返回。 在尝试调用该插件之前,您需要检查一下。

您可以将使用插件的代码放在该onload函数中

tk.onload = tk.onreadystatechange = function() {
    var rs = this.readyState;
    if (rs && rs != 'complete' && rs != 'loaded'){
         $(function(){
              $('#test').jq_plugin();
         });
    }
};

您可以设置布尔值tkHasLoaded = false ,然后在onload函数中将其设置为true。 在尝试使用插件之前检查一下。

暂无
暂无

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

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