Skip to content Skip to sidebar Skip to footer

How To Detect When Iframe Starts Loading Another Page?

I'm trying to hide an element in same-origin iframe. However, this son of a bi*ch blinks for a few ms before getting hidden. So what I did was added display: none and remove it aft

Solution 1:

You can make use of load event on the iframe as such,

$('iframe').on('load', function(){
    console.log('Iframe Loaded');
});

The iframe's load event is also called every time it's src changes.


Solution 2:

$(document).ready(function(){
    $('.iFrame_class').load(function(){
        console.log('frame loaded');
    });
});

Alternatively on start load solution:

Custom attribute for iframe:

iframe class="iFrame" src="some site" started="0"

Put this code to iframed page:

  window.parent.$('.iFrame').attr("started","0"); //makes iframe started attr to false on page load
  $(document.body).on("click","a", function() {
     window.parent.$('.iFrame').attr("started","1");// makes iframe started attr to true for all clicked links
  });

And listen; is started attribute changed to 1 on parent page?


Solution 3:

I fixed the damn blinking by making 2 iframes and showing 2nd while 1st one is loading. While 1st one is loading, it's also hidden, becomes unhidden after it finishes loading. Anyway, here is my code, should help someone:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<style>
iframe.js
{
    display: none;
}
iframe.unclickable
{
    pointer-events: none;
}
</style>

<script>
$(document).ready(function()
{
    $('#iframeID1').on('load', function()
    {
    $('#iframeID1').contents().find('a[href!="javascript:void(0)"]').filter('a[target!="_blank"]').filter('a[target!="_top"]').filter('a[target!="_parent"]').on('click', function()
        {
            $('#iframeID1').addClass('js');
            $('#iframeID2').removeClass('js');
        });
        $('#iframeID1').contents().find('#mySidenav').remove();
        $('#iframeID1').removeClass('js');
        $('#iframeID2').addClass('js');
        $('#iframeID2').contents().find('html').html($('#iframeID1').contents().find('html').html());

    });


});
</script>
</head>

<body>
<iframe id="iframeID1" height="800px" width="800px"  src="https://www.w3schools.com/" class="js"></iframe>
<iframe id="iframeID2" height="800px" width="800px" src="https://www.w3schools.com/" class="js unclickable" ></iframe>
<script>

</script>
</body>

</html>

Post a Comment for "How To Detect When Iframe Starts Loading Another Page?"