正文
本文首发
我的博客 - blog.cdswyda.com
,转载务必保留作者和出处,以便追溯和错误修正。
本文关键点:
window.onload
和 页面上
ajax
的成功回调到底哪个先触发。
答案是
不确定
。
问题详情
之前遇到一个现象,在父页面弹出一个Dialog加载一个子页面,在onload回调中传递一个参数给子页面,子页面异步ajax成功回调中要使用这个变量。
然而出现的情况是在ajax的成功回调中大多数情况下是取不到这个在onload传来的值,但是偶尔又是可以的。
查阅此Dialog源码,以上逻辑可以进行如下简化。
父页面:
<iframe id="iframe" src="./iframe.html" onload="onLoad()" frameborder="0"></iframe>
<script>
function onLoad() {
console.log('iframe load');
document.getElementsByTagName('iframe')[0].contentWindow.onLoad('load');
}
</script>
子页面:
<script>
$.ajax('./test.json').done(function (a) {
console.log('ajax结果');
console.log(a);
});
function onLoad(e) {
console.log('window onload')
console.log(e);
};
</script>
由于iframe的
onload
即要加载页面的
window.onload
,因此情况可以进一步简化为一个页面中到底是
window.onload
先触发还是
ajax
的成功回调先触发。
测试代码:
<script>
$.ajax('./test.json').done(function (a) {
console.log('ajax结果');
console.log(a);
});
function onLoad(e) {
console.log('window onload')
console.log(e);
};
window.onload = onLoad;
</script>
这个页面除了在测试的script之前引入了jQuery没有其他代码,应该毫无疑问,是
window.onload
先触发,之后才是
ajax
的成功结果。
结果也证明是
window.onload
先触发,上面代码在浏览器运行结果为:
// window onload
// Event {}
// ajax结果
// {}
MDN上关于
window.onload
有如下解释:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
那么问题就来了,如果必然是 window.onload 先触发,那么是不可能出现最开始的问题的。