如何检测iframe是否已加载?

Rou*_*uge 98 html javascript iframe jquery

我试图检查用户单击按钮后是否加载了iframe.

我有

$('#MainPopupIframe').load(function(){
    console.log('load the iframe')
    //the console won't show anything even if the iframe is loaded.
})
Run Code Online (Sandbox Code Playgroud)

HTML

<button id='click'>click me</button>

//the iframe is created after the user clicks the button.
<iframe id='MainPopupIframe' src='http://...' />...</iframe>
Run Code Online (Sandbox Code Playgroud)

有什么建议?

顺便说一句,我的iframe是动态创建的.它不会加载初始页面加载.

The*_*pha 179

你可以尝试这个(使用jQuery)

$(function(){
    $('#MainPopupIframe').load(function(){
        $(this).show();
        console.log('iframe loaded successfully')
    });
        
    $('#click').on('click', function(){
        $('#MainPopupIframe').attr('src', 'https://heera.it');    
    });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='click'>click me</button>

<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
Run Code Online (Sandbox Code Playgroud)

jsfiddle DEMO.

更新:使用普通javascript

window.onload=function(){
    var ifr=document.getElementById('MainPopupIframe');
    ifr.onload=function(){
        this.style.display='block';
        console.log('laod the iframe')
    };
    var btn=document.getElementById('click');    
    btn.onclick=function(){
        ifr.src='https://heera.it';    
    };
};
Run Code Online (Sandbox Code Playgroud)
<button id='click'>click me</button>

<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
Run Code Online (Sandbox Code Playgroud)

jsfiddle DEMO.

更新:你也可以尝试这个(动态iframe)

$(function(){
    $('#click').on('click', function(){
        var ifr=$('<iframe/>', {
            id:'MainPopupIframe',
            src:'https://heera.it',
            style:'display:none;width:320px;height:400px',
            load:function(){
                $(this).show();
                alert('iframe loaded !');
            }
        });
        $('body').append(ifr);    
    });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='click'>click me</button><br />
Run Code Online (Sandbox Code Playgroud)

jsfiddle DEMO.

  • 不推荐使用`load()`,但这只是因为它与ajax函数冲突.推荐的替换只是`on("load")`.(不幸的是,文档并没有明确说明这就是你需要做的全部.) (19认同)
  • 香草溶液很棒. (2认同)