Sobes.tech
Junior

How to find out that the iframe has loaded?

sobes.tech AI

Answer from AI

There are several ways:

  1. Using the load event: The most common and reliable method.

    const iframeElement = document.getElementById('myIframe');
    
    iframeElement.onload = function() {
      // Code executed after iframe loads
      console.log('iframe loaded!');
    };
    
  2. Using the onload attribute in HTML:

    <iframe src="somepage.html" onload="iframeLoaded()"></iframe>
    
    <script>
    function iframeLoaded() {
      // Code after loading
      console.log('iframe loaded via onload attribute!');
    }
    </script>
    
  3. Checking document.readyState inside the iframe (if you have access to the iframe content):

    const iframeElement = document.getElementById('myIframe');
    
    iframeElement.onload = function() {
      const iframeDoc = iframeElement.contentDocument || iframeElement.contentWindow.document;
    
      if (iframeDoc.readyState === 'complete') {
        // Code after the DOM inside iframe is fully loaded
        console.log('iframe DOM fully loaded!');
      }
    };
    

    This method is less reliable for detecting the readiness of all resources (images, scripts) inside the iframe; the load event is more suitable for that.

  4. Using addEventListener: A more modern way to subscribe to the event.

    const iframeElement = document.getElementById('myIframe');
    
    iframeElement.addEventListener('load', function() {
      // Code after iframe loads
      console.log('iframe loaded using addEventListener!');
    });
    

The choice of method depends on the context and preferences, but the load event is the most universal and reliable for detecting the full load of the iframe, including all its resources.