代码之家  ›  专栏  ›  技术社区  ›  Brian

javascript iframe缓存问题

  •  1
  • Brian  · 技术社区  · 14 年前

    我有一个iframe,它通过javascript加载一些javascript。仅在Internet Explorer中,只有当且仅当IE有一个javascript的缓存副本时,这才有效。这意味着重新加载页面(或者触发脚本再次运行,如果它被困在某个函数或其他什么东西中)将导致该代码工作,否则它将不工作。尤其是,document.write调用失败。

    主页面:

    <iframe height = "200" width = "200" id = "happy">
    </iframe>
    <script type="text/javascript">
     var a = document.getElementById("happy");
     scripttxt = '<a href="#" id="joy">JOY</a><'+'script type="text/javascript" src="fail.js"></'+'script>';
     a.src = "about:blank"; 
     a.contentWindow.document.open();
     a.contentWindow.document.write("<h3>Preview:</h3>" + scripttxt + "");
     a.contentWindow.document.close();
    </script>
    

    失败.js:

    document.write(document.getElementById("joy"));
    

    我知道我可以用有条件的注释让IE跳过 document.open() document.close() 在主页的脚本中,但是让ie跳过document.open()和document.close()会让人觉得有点不习惯(编辑)。 在IE中破坏其他东西 .

    编辑: 当它正常工作时,iframe将在预览标题下包含文本: JOYhttp://mymachine:myport/mainpage.htm# “欢乐”是一个超链接。如果失败,它将忽略 http://mymachine:myport/mainpage.htm# . 我不在乎document.write如何处理 a 节点,只是它能够成功地获取元素并成功地编写一些内容。

    在贾斯汀的建议下,我也尝试了这个版本的脚本,但它的行为完全相同:

    var a = document.getElementById("happy");
    a.src = "about:blank";  
    r = document.createElement("a");
    r.id="joy";
    r.href="#";
    r.innerText="JOY";
    s = document.createElement("script");
    s.src="fail.js";    
    a.contentWindow.document.body.appendChild(r);
    a.contentWindow.document.body.appendChild(s);
    
    3 回复  |  直到 14 年前
        1
  •  0
  •   Justin Johnson    14 年前

    你为什么用 document.write ?相反,尝试附加一个脚本节点。

    var d = document.getElementById("happy"),
        s = document.createElement("script");
    
    s.src= "http://asdf.com/asdf.js";
    d.contentWindow.document.body.appendChild(s);
    
        2
  •  0
  •   Pointy    14 年前

    尝试将代码更改为如下所示:

    // ...
    var doc = a.contentWindow.document.open();
    doc.write("<h3>Preview:</h3>" + scripttxt + "");
    doc.close();
    

    哦,等等,不,这也有类似的问题。

    好吧,把你的文档和“document.write”混搭在一起还是有点古怪。这里的总体目标是什么?您不能用其他方式向文档添加内容吗?

    不过,我想我理解您的意思:有人可能会期望浏览器遵守正常的操作方式,加载脚本(并等待HTTP完成),运行脚本-这意味着脚本中的“写入”调用应该仍然具有docu打开-然后返回。然后,考虑到我们所讨论的是一个单线程环境,我觉得这有点冒险。

        3
  •  0
  •   Brian    14 年前

    我目前的解决方案是:

    变化

    a.contentWindow.document.close();
    

    if (!isIE) {a.contentWindow.document.close();}
    

    并在脚本上方添加此代码:

    <script type='text/javascript'>
        isIE = false;
    </script>
    <!--[if IE]>    
    <script type='text/javascript'>
        isIE = true;
    </script>
    <![endif]-->
    

    这个办法让我很难过。