【问题标题】:How can I determine whether jQuery is fully initialized?如何确定 jQuery 是否已完全初始化?
【发布时间】:2016-03-19 18:53:28
【问题描述】:

我正在使用 jQuery 编写书签。看起来像javascript:document.write('<script src="path/to/loader.js"></script>'),而loader.js 做了初始化工作:

check_the_environment();

document.head.innerHTML='<meta charset=utf-8>';
document.body.innerHTML='(the webpage)';

var jq=document.createElement('script');
jq.src='path/to/jquery.min.js';
document.head.appendChild(jq);

function load_core() {
    if(window.$)
        eval('(core js code)');
    else
      setTimeout(load_core,50);
}
load_core();

加载器在 jQuery 可用后加载核心 javascript 代码。

但有时我的核心代码中会出现此错误:

$(...).on is not a function

尽管设置了 $ 变量,但 jQuery 似乎仍在初始化自己。

所以,在加载器加载核心代码之前,我需要等待 jQuery 完全初始化。我该怎么做?

使用 $(document).ready(...) 的传统方式是不可行的,因为 jQuery 是在 网页准备就绪之后加载的。

这里是检查解决方案是否有效的最小 Python 代码:

import cherrypy

mod='''
var htmlroot=document.getElementsByTagName('html')[0];

function load_core() {
  if(window.jQuery)
    jQuery(function(){
        alert($(document).on);
    });
  else
    setTimeout(load_core,10);
}

if(!document.head)
  htmlroot.appendChild(document.createElement('head'));

var jquery=document.createElement('script');
jquery.src='http://libs.useso.com/js/jquery/2.1.1/jquery.min.js';
document.head.appendChild(jquery);

load_core();
'''

class Website:
    @cherrypy.expose()
    def mod(self,_time):
        return mod

    @cherrypy.expose()
    def index(self):
        return '''<a href="javascript:document.write('<script src=/mod/'+(+new Date())+' ></script>')">Mod</a>'''

cherrypy.quickstart(Website(),'/');

【问题讨论】:

标签: javascript jquery bookmarklet


【解决方案1】:

正确且万无一失的方法是:

jQuery(function(){
    // code
});

由于 jQuery 可能在 noConflict 模式下加载,$ 变量可能尚未初始化。

为了提高工作效率,还可以使用以下方法访问jQuery 范围内的$ var。

jQuery(function($){
    // you can use $ without worrying about conflicts now
});

【讨论】:

  • jQuery 仍将是未定义的,因为脚本是异步加载的。我想我将不得不使用onload 事件...
  • 该解决方案不起作用,因为jQuery(function($){}) 中的代码永远不会被执行。请参阅我的问题以获取一个小程序来验证这一点。
【解决方案2】:

您可以检查 $ 的类型如下

if(typeof $ == "function"){
    //Jquery loaded
}

【讨论】:

    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    相关资源
    最近更新 更多