如何确定jQuery是否已完全初始化

How can I determine whether jQuery is fully initialized?

本文关键字:初始化 是否 何确定 jQuery      更新时间:2023-09-26

我正在使用jQuery编写一个bookmarklet。它看起来像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(),'/');

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

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

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

为了提高生产力,以下内容也可以用于访问jQuery范围内的$var。

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

您可以在下面检查$的类型

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