Chrome 无法正确观察脚本标签上的 onload 事件?
我正在使用 Javascript 动态加载外部 Javascript 文件,在我的应用程序中,我需要知道这些脚本何时完全加载到内存中,然后才能继续其余的进程。我尝试使用以下代码来监视附加到头部的脚本标签上的 onload
事件:
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.onload = scriptLoaded;
newScript.src = '/path/to/file.js';
headID.appendChild(newScript);
来源:http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS< /sub>
这在 FireFox(最新版本的 Windows 和 OS X)中效果很好,但是 Chrome(同样在 Windows 和 OS X 版本中)似乎无法正确观察事件,并且过早调用回调函数。
有什么想法吗?
I am using Javascript to dynamically load in external Javascript files, and in my application I need to know when those scripts are fully loaded into memory before the rest of process can continue. I have tried the following code to monitor the onload
event on the script tags being appened to the head:
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.onload = scriptLoaded;
newScript.src = '/path/to/file.js';
headID.appendChild(newScript);
Source: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS
This works great in FireFox (latest version Windows and OS X) however it appears that Chrome (again in both windows and OS X versions) does not observe the event properly, and the callback function is invoked prematurely.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
设法通过用 jQuery 重写来解决这个问题:
不知道为什么会解决这个问题,也许 chrome 只是不喜欢在第一个实现中使用纯 javascript 创建脚本标签的方式。 耸耸肩
Managed to solve the issue by rewriting it with jQuery:
Not sure why this fixes it, maybe chrome just didn't like the way the script tag was being created in the first implementation using pure javascript. shrug
您可以尝试将函数调用包装在另一个函数中。我遇到了一些像您所描述的错误,并且执行以下操作有时会有所帮助:
Chrome 似乎正在尝试评估
scriptLoaded
以便将返回值分配给newScript.onload< /代码>。
You may try wrapping your function call in another function. I've had some error like you're describing and doing the following sometimes helps:
It almost seems like Chrome is trying to evaluate
scriptLoaded
in order to assign the return value tonewScript.onload
.