Home > Web Front-end > JS Tutorial > body text

**How to Reliably Determine if an iFrame Has Loaded and Contains Content?**

DDD
Release: 2024-10-24 21:48:03
Original
704 people have browsed it

**How to Reliably Determine if an iFrame Has Loaded and Contains Content?**

Determining iFrame Load Status for Content Detection

In web development, it's often necessary to dynamically load content into an iFrame. To ensure proper functionality and avoid potential errors, it's crucial to determine when the iFrame has successfully loaded and contains content.

Problem:

Consider an iFrame with a variable loading time. You need a way to detect whether the iFrame has finished loading or acquired content. Approaches such as iframe.contents().find() or iframe.load(function()) may not always be feasible.

Solution:

Here's a JavaScript function that effectively checks for an iFrame's loaded state:

<code class="javascript">function checkIframeLoaded() {
    // Get iframe reference
    var iframe = document.getElementById('i_frame');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (iframeDoc.readyState == 'complete') {
        // Loading is complete
        afterLoading();
        return;
    } 

    // Set timeout for re-checking
    window.setTimeout(checkIframeLoaded, 100);
}

function afterLoading(){
    // Execute desired code after iFrame load
}</code>
Copy after login

In the of your HTML document, add the following:

<code class="html"><body onload="checkIframeLoaded();"></code>
Copy after login

This function periodically checks the iFrame's readyState property, which indicates its load status. When readyState equals 'complete,' the iFrame has loaded, and you can execute any desired code through the afterLoading() function.

The above is the detailed content of **How to Reliably Determine if an iFrame Has Loaded and Contains Content?**. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!