Junior
How to find out that the iframe has loaded?
sobes.tech AI
Answer from AI
There are several ways:
-
Using the
loadevent: The most common and reliable method.const iframeElement = document.getElementById('myIframe'); iframeElement.onload = function() { // Code executed after iframe loads console.log('iframe loaded!'); }; -
Using the
onloadattribute in HTML:<iframe src="somepage.html" onload="iframeLoaded()"></iframe> <script> function iframeLoaded() { // Code after loading console.log('iframe loaded via onload attribute!'); } </script> -
Checking
document.readyStateinside 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
loadevent is more suitable for that. -
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.