Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show spinner till iframe loads with a http post response

I have two websites A.com and B.com. I have to embedd B.com in an iframe in A.com. I cannot make any changes at B.com

B.com only works with post requests with some post data . I have this working as following

<!--This is the div inside which I will embedd the iframe-->
<div id="frameDiv"></div>

<script type="text/javascript">

    //Create iframe
    var $ifr = $('<iframe name="myFrame" id="myFrame"></iframe>');

    //create form
    var $form = $('<form action="B.com" method="post" target="myFrame"></form>');

    //Append hidden field to form to pass postData
    $form.append($('<input type="hidden" name="dataName"><input>').val('data'));

    //Append form to the iframe and then append iframe to the div    
    $('#frameDiv').append($ifr.append($form));

    $form.submit();
</script>

Now, B.com loads perfectly within the iframe with response to the post request. But B.com is slow. I want to show a spinner inside the #frameDiv till the iframe loads. How can I do this?

This is what I tried:

$('#frameDiv').append($spinnerImage)

//Does not work, fires immediately
$ifr.load(function(){
    //Hide the spinner image
});

//Does not work, fires immediately
$ifr.ready(function(){
    //Hide the spinner image
});

If B.Com was a simple get and was set as the src attribute of the iframe, jQuery load method does the trick. But in this case it does not.

Any help is appreciated :)

like image 949
labroo Avatar asked Jun 24 '12 23:06

labroo


2 Answers

You can try binding a new load event listener within the initial load event handler of the iframe. The following works on same domain iFrame:

$ifr.load(function(){
    /* bind new load event listener for next load*/
    $(this).load(function(){
         /* hide spinner*/
    })
});
like image 31
charlietfl Avatar answered Nov 03 '22 21:11

charlietfl


@charlietfl's answer is correct and it works. I just wanted to share this other method I found out that also works.

Just set the background of the iframe to the spinner :)

#myFrame
{
    background-image: url('/content/images/spinner.gif');   
    background-repeat: no-repeat;
}

When B.com loads, the new document hides the spinner..

Any idea which approach is preferred ??

like image 186
labroo Avatar answered Nov 03 '22 23:11

labroo