JavaScript 在 Iframe 加载时显示加载 gif

JavaScript Show loading gif while Iframe loads

本文关键字:加载 显示 gif JavaScript Iframe      更新时间:2023-09-26

我需要在 iframe 加载时显示加载 GIF。
这就是我想出的:

<div id="m-load" style="position:relative;top:45%;left:45%;">
<img src="images/loader.gif"/></div>
<iframe src="http://myserver.com/myfile.html" id="m-iframe"></iframe>

在我输入的 iframe 源文件中:(myfile.html)

<head>
<script>
top.document.getElementById('m-load').style.display ="none";
</script>
</head>

但这在 Firefox 中不起作用(权限被拒绝)。
还有其他方法可以实现这一目标吗?

您需要

使用onload事件在同一页面上执行此操作,该事件在所有 iframe 加载后触发,如下所示:

// show loading image
window.onload = function(){
  // hide loading image
}

<img id="img" src="images/loader.gif"/></div>
<script>
window.onload = function(){
   document.getElementById('img').style.display = "none";
}
</script>
不允许

iframes随意访问父内容。假设黑客在您的页面中发现了一个漏洞(例如,您有一个评论表单,允许出于任何目的iframe。如果他们可以访问父级,他们就可以遍历您的网站。

您可以使用 postMessage 代替。由于页面和 iframe 现在都同意如何通信,以及什么构成有效通信,因此您不能任意访问您的页面。有一个很好的教程在 http://robertnyman.com/2010/03/18/postmessage-in-html5-to-send-messages-between-windows-and-iframes/