Chrome中的窗口onload事件失败 [英] window onload event fails in Chrome
问题描述
我正在从javascript中添加一些<script/>
标记以加载某些库(例如jquery).加载所有库后,我将执行主代码.为了等到一切就绪,我使用类似于此答案中的解决方案(在网络上找到).
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).
现在,故事: 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控制台中出现错误.
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.
这是否意味着我严重滥用addEventListener
?如果是,它的正确用法是什么?如何真的等到所有脚本加载完毕?
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?
谢谢!
PS尚未在任何其他浏览器中对其进行测试,因此,如果它在其他地方失败,请发表评论.
Thanks!
PS Didn't test it in any other browsers yet, so please comment if it's failing somewhere else.
修改
如果在测试之前等待一秒钟(使用setTimout
),则成功率将提高到100%.示例 http://jsfiddle.net/EH84z/1/
edit
if I wait one second (using setTimout
) before testing, success rate increases to 100%. An example http://jsfiddle.net/EH84z/1/
推荐答案
您必须将load
事件附加到jQuery脚本标签,而不是window
对象.
You have to attach the load
event to the jQuery script tag, not the window
object.
尝试一下:
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);
// attach it to the script tag
addEvent(a, "load", function() {
console.log(window.jQuery + ' ' + window.$);
$(document);
}, false);
}
这篇关于Chrome中的窗口onload事件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!