嵌套异步 JavaScript
我正在使用指定的技术 http://friendbit.com/js/lazy-loading- asyncronous-javascript/ 在触发 window.onload() 时加载外部 javascript。但是,如果脚本本身包含加载事件处理程序的某些注册,那么它们可能不会被调用,因为事件已(以某种方式)传递。为了确认,我将以下代码添加到如上所述加载的外部javascript文件中:
(function() {
if (window.attachEvent)
window.attachEvent('onload', alert("ok"));
else
window.addEventListener('load', alert("ok"), false);
})();
实际上出现了这个警报,这让我思考,onload是否被调用两次,或者加载javascript是否意味着加载脚本,运行其“全局” ”部分,然后转向下一位听众。在后一种情况下,如果在运行其“全局”部分时将另一个侦听器添加到 onload 事件,则此行为是正确的。但我不确定这一点,如果更有经验的人能够澄清/确认这一点,我将不胜感激。
I am using the technique specified http://friendlybit.com/js/lazy-loading-asyncronous-javascript/ to load external javascript when the window.onload() is triggered. But if the script itself contains some registration of load event handler then they might not get called as the event has been (somehow) passed. In order to confirm, I added the following code to the external javascript file that is loaded as mentioned above:
(function() {
if (window.attachEvent)
window.attachEvent('onload', alert("ok"));
else
window.addEventListener('load', alert("ok"), false);
})();
This alert actually appears which make me think, whether the onload is called twice or does loading javascript means loading the script, running its "global" part and then moving on to the next listener. In the latter case, if another listener is added to onload event while running its "global" part then this behavior is correct. But I am not sure of this and would appreciate if someone more experienced could clarify/confirm it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信警报是在附加事件时调用的,而不是在加载窗口时调用的。这是因为您正在执行警报函数,然后将警报的结果(将为空)作为第二个参数传递给attachEvent。
您正在执行的本质上是:
要测试您在问题中描述的内容,您需要修改代码:
I believe that alert is being called when the event is attached, not when the window is loaded. That's because you're executing the alert function, and then passing the result of alert (which will be null) as the second parameter to attachEvent.
What you are executing is essentially:
To test what you describe in your question, you need to modify your code: