How does $('iframe').ready() method work in jQuery?

The $('iframe').ready() method in jQuery is used to execute code when an iframe and its content are fully loaded. However, it's important to note that the .ready() method doesn't work reliably with iframes due to cross-origin restrictions and timing issues. Instead, you should use the load event for iframes.

Here's an example wherein the iframe size is larger than the page. We will scroll to the top of the page whenever the iframe loads using jQuery −

Example

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
        $("button").click(function(){
          $('#iframe').on('load', function(){
            $(window).scrollTop(0);
            alert("Iframe loaded and page scrolled to top!");
          });
          // Reload the iframe to trigger the load event
          $('#iframe')[0].src = $('#iframe')[0].src;
        });
      });
    </script>
  </head>
  <body>
    <h3>Click the button to reload iframe and scroll to top</h3>
    <iframe frameborder="2" height="600" id="iframe" src="https://www.example.com" width="800"></iframe>
    <br><br>
    <button>Reload Iframe and Scroll to Top</button>
    <div style="height: 1000px; background: linear-gradient(to bottom, #f0f0f0, #ccc);">
      <p>This is additional content to demonstrate scrolling behavior.</p>
    </div>
  </body>
</html>

Better Approach Using Load Event

Since .ready() doesn't work reliably with iframes, here's the recommended approach using the load event −

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
        $('#myIframe').on('load', function(){
          console.log("Iframe content loaded successfully!");
          $(window).scrollTop(0);
        });
      });
    </script>
  </head>
  <body>
    <h3>Iframe Load Event Example</h3>
    <iframe id="myIframe" src="https://www.example.com" width="800" height="400" frameborder="1"></iframe>
    <div style="height: 800px; background: #f5f5f5; padding: 20px;">
      <p>Scroll down and then reload the page to see the scroll-to-top effect when iframe loads.</p>
    </div>
  </body>
</html>

The load event is more reliable than ready() for iframes because it fires when the iframe's content is completely loaded, including all images and stylesheets. This approach ensures better cross-browser compatibility and more predictable behavior.

Updated on: 2026-03-13T20:50:08+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements