两个Javascript无法创建两个iframe,只有最后一个javascript创建iframe

时间:2016-09-15 10:07:37

标签: javascript html iframe

我有两个用于在页面上动态创建iframe的脚本,但只有最后一个可以工作,但如果我在单独的页面上使用它们都可以正常工作。

<script id='vr_NTgtLxxx'>
window.options = {
    api_key: 'NTgtLxxx',
    height: '100%',
    width: '100%',
    min_height: '1000px'
};
var s = document.createElement('script');
s.src = "http://www.example.com/embed.js";
s.async = true;
document.body.appendChild(s);
</script>


<script id='vr_My0tNxxx'>
window.options_search = {
    api_key_search: 'My0tNxxx',
    height: '100%',
    width: '100%',
    min_height: '1000px',
    'title': 'search'
};
var sa = document.createElement('script');
sa.src = "http://www.example.com/embed-search.js";
sa.async = true;
document.body.appendChild(sa);
</script>
  

以下是iframe构建代码

window.onload=function(){
        var container_s=document.createElement("div");
            container_s.setAttribute("id", "div_");  

        var span_s =document.createElement("span_s");
            span_s.setAttribute("id", "span_s_");
            span_s.style.fontFamily="arial"; 
            span_s.style.fontWeight="bold"; 
            span_s.style.textAlign="center"; 
            span_s.style.display ="Block"; 

        var loader_message_s = document.createTextNode("...."); 
            span_s.appendChild(loader_message_s); 
            container_s.appendChild(span_s);

        var ifrm_s = document.createElement("iframe");
        ifrm_s.setAttribute("src","SRC_URL");
        ifrm_s.style.width = "100%";
        ifrm_s.style.minHeight = "1000px";
        ifrm_s.frameBorder=0;
        if(window.options_search.width){
            ifrm_s.style.width = window.options_search.width;
        }
        ifrm_s.style.height = "100%";
        if(window.options_search.height){
            ifrm_s.style.height = window.options_search.height;
        }
        if(window.options_search.min_height){
            ifrm_s.style.minHeight  = window.options_search.height;
        }   

        if(window.options_search.border){
            ifrm_s.style.border = window.options_search.border;
        }           
        ifrm_s.setAttribute("id", key_search_s);
        ifrm_s.setAttribute("onload", 'frameload_s("span_s_'+key_search_s+'")');
        container_s.appendChild(ifrm_s);
        var s_s = document.getElementById("vr_"+key_search_s);
        s_s.parentNode.insertBefore(container_s, s_s);
}

我在这里添加了用于创建iframe的代码

1 个答案:

答案 0 :(得分:0)

问题在覆盖window.onload函数定义中进行中继。请改用addEventListener(event, callback)

这是一个减少相同问题的简化示例。

&#13;
&#13;
window.onload = function(){
  console.log('Window loaded #1'); // Will not excecute
}
window.onload = function(){
  console.log('Window loaded #2'); // Window loaded #2
}
&#13;
&#13;
&#13;

使用addEventListener

的工作解决方案

&#13;
&#13;
window.addEventListener('load', function(){
    console.log('Window loaded #1'); // Window loaded #1
});
window.addEventListener('load', function(){
    console.log('Window loaded #2'); // Window loaded #2
});
&#13;
&#13;
&#13;