funerr
funerr

Reputation: 8176

JavaScript Show loading gif while Iframe loads

I need a loading GIF to show up while the iframe is loading.
This is what I came up with:

<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>

And in the iframe source file I entered:(myfile.html)

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

But this won't work in Firefox (permission denied).
Any other way of achieving this?

Upvotes: 3

Views: 9469

Answers (2)

David Souther
David Souther

Reputation: 8184

iframes are not allowed to just access parent content willy-nilly. Suppose a hacker finds a vulnerability in your page (say, you have a comment form that allows iframes for whatever purpose. If they can just access the parent, they get to walk all over your site.

You could use instead postMessage. Because both the page and the iframe now agree on how to communicate, and what constitutes valid communication, you don't have arbitrary access to your page. There's a good tutorial at http://robertnyman.com/2010/03/18/postmessage-in-html5-to-send-messages-between-windows-and-iframes/

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382919

You need to do it on the same page using onload event which fires after all iframes are loaded like this:

// 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>

Upvotes: 6

Related Questions