如何在整个页面加载(包括图像)时启动 JS 代码(真实完整)
我想在整个页面加载完成后执行脚本。
目前的做法是:
window.onload=document.getElementById('loaded').value=1;
这不太好,因为有些图像仍在加载中,并且页面尚未真正完成加载。我做错了什么?
当然在 Chrome 和 Firefox 中对我来说不起作用。问题是我之后启动了一个代码,该代码返回状态 204,这会阻止未来的加载。但它表明这个 204 状态是在页面完成加载之前返回的。所以我需要在页面真正加载后执行我的代码。
编辑
设置一个页面,
<iframe id="myframe" height=1 width=1></iframe>
<script type="text/javascript">
window.onload=document.getElementById('myframe').src='http://link to a frame braker page';
</script>
当您将上述代码放入页面时,它会进行框架破坏,它会在页面完全加载之前加载 iframe。只需在 iframe 页面中放置一个警报,然后在父页面包含大图像等的较慢服务器上尝试。
I want to execute a script after the whole page has loaded, when it's complete.
The current way is:
window.onload=document.getElementById('loaded').value=1;
Which is not good, as some images are still in load, and the page has not completed loading truly. What I am doing wrong?
Certainly doesn't work for me in Chrome and Firefox. The thing is I launch a code after, that returns status 204, and this blocks future loads. But it seams this 204 status is returned way before the page has finished loading. So I need to execute my code after the page has truly loaded.
EDIT
setup a page, that does framebreaking
<iframe id="myframe" height=1 width=1></iframe>
<script type="text/javascript">
window.onload=document.getElementById('myframe').src='http://link to a frame braker page';
</script>
when you put the above code to a page, it loads the iframe before the page is fully loaded. Simply put an alert in the iframe page, and try out on a slower server where your parent page contains large images etc..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你忘了把它变成一个函数。你的意思是:
显然,这作为负载检测器并不是很有效。你的意思大概是:
You've forgotten to turn that into a function. What you're saying is:
Obviously that's not very effective as a load detector. What you meant was probably:
window.onload
事件在触发之前应等待图像加载:您可能需要查看以下 Stack Overflow 帖子以进一步阅读:
更新:
您的实现无法正常工作的原因已由 bobince 在另一个答案中。解决方案是使用:
The
window.onload
event should wait for images to load before it is fired:You may want to check out the following Stack Overflow post for further reading:
UPDATE:
The reason why your implementation is not working has identified by bobince in another answer. The solution is to use:
如果您可以使用 Jquery,请查看 FrameReady 插件。
检查这个所以问题。欲了解更多信息
If you can use Jquery, have a look to FrameReady plugin.
Check this SO question. for further information