【发布时间】: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(),'/');
【问题讨论】:
-
首先尝试将
window.$换成window.jQuery
标签: javascript jquery bookmarklet