Chrome 中的窗口 onload 事件失败
我从 javascript 添加一些 标签来加载一些库(例如,jquery)。加载所有库后,我执行主代码。为了等到一切准备就绪,我使用类似于 这个答案中的解决方案(在网上找到的)。
现在,故事: http://jsfiddle.net/EH84z/
function load_javascript(src) {
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = src;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(a, s);
}
load_javascript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js');
function addEvent(elm, evType, fn, useCapture) {
//Credit: Function written by Scott Andrews
//(slightly modified)
var ret = 0;
if (elm.addEventListener) {
ret = elm.addEventListener(evType, fn, useCapture);
} else if (elm.attachEvent) {
ret = elm.attachEvent('on' + evType, fn);
} else {
elm['on' + evType] = fn;
}
return ret;
}
addEvent(window, "load", function() {
console.log(window.jQuery + ' ' + window.$);
$(document);
}, false);
它在 Firefox 中工作正常,但相当在 Chrome 中经常失败。每当我按下 jsfiddle“运行”按钮时,回调就会在加载 JQuery 之前执行,从而在 Chrome 控制台中给出错误。
这是否意味着我严重滥用了 addEventListener
?如果是,它的正确用途是什么?我如何真正等待所有脚本加载?
谢谢!
PS 尚未在任何其他浏览器中进行测试,因此如果在其他地方失败,请发表评论。
编辑
如果我在测试前等待一秒钟(使用 setTimout),成功率会增加到 100%。示例 http://jsfiddle.net/EH84z/1/
I'm adding some <script/>
tags from javascript to load some libraries (e.g., jquery). When all libraries are loaded, I execute main code. To wait until everything's ready, I use solution similar to the one in this answer (found it on the web).
Now, the story: http://jsfiddle.net/EH84z/
function load_javascript(src) {
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = src;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(a, s);
}
load_javascript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js');
function addEvent(elm, evType, fn, useCapture) {
//Credit: Function written by Scott Andrews
//(slightly modified)
var ret = 0;
if (elm.addEventListener) {
ret = elm.addEventListener(evType, fn, useCapture);
} else if (elm.attachEvent) {
ret = elm.attachEvent('on' + evType, fn);
} else {
elm['on' + evType] = fn;
}
return ret;
}
addEvent(window, "load", function() {
console.log(window.jQuery + ' ' + window.$);
$(document);
}, false);
It works fine in Firefox, but quite often fails in Chrome. Every second time I press jsfiddle 'run' button, callback is executed before JQuery is loaded, thus giving error in Chrome console.
Does it mean I misuse addEventListener
horribly? If yes, what's the correct use for it and how do I really wait until all scripts are loaded?
Thanks!
PS Didn't test it in any other browsers yet, so please comment if it's failing somewhere else.
edit
if I wait one second (using setTimout
) before testing, success rate increases to 100%. An example http://jsfiddle.net/EH84z/1/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须将
load
事件附加到 jQuery 脚本标记,而不是window
对象。试试这个:
You have to attach the
load
event to the jQuery script tag, not thewindow
object.Try this: