document.write令人惊讶的行为

时间:2015-04-02 05:42:05

标签: javascript document.write

在我的页面上,我正在使用document.write编写外部JS和iframe,如下所示

document.write("<sc" + "ript src=\"http://d2hzts1b0z7hqh.cloudfront.net/arb.js\"></script>");
document.write("<iframe id='mytestframe'></iframe>");
document.close();
var frame = document.getElementById("mytestframe");
console.log(frame);

最后一个console.log语句打印的帧值为'null'。但是如果我注释掉第一行document.write("<sc" + "ript src=\"http://d2hzts1b0z7hqh.cloudfront.net/arb.js\"></sc" + "ript>");,则log语句会打印一个节点实例。

有人可以解释这种令人惊讶的行为背后的原因。

您可以使用JSFiddle here

2 个答案:

答案 0 :(得分:1)

您过早地调用 getElementById ,将其延迟直到加载事件发生,或者将其放在调用 document.write 的下面的另一个脚本元素中。

以下对我来说很好:

document.write('Hello World');
document.write('<script src="http://d2hzts1b0z7hqh.cloudfront.net/arb.js"><\/script>');
document.write('<iframe id="mytestframe"><\/iframe>');
document.close();

// Delay looking for iframe until page is loaded
window.onload = function() {
  var frame = document.getElementById("mytestframe");
  console.log(frame);
};

请注意,您需要在脚本元素中的所有结束标记中引用“/”,因此<\/引用所有结尾标记(例如<\/iframe>),而不只是<\/script>

答案 1 :(得分:1)

这是我的理论: 当您使用src添加Script标记时,浏览器将首先加载js文件,然后继续解析HTML标记。否则,它会立即解析它们。 这是我的测试代码。仅用Firefox测试过。 HTML文件t1.htm:

<html >
<head>

</head>
<body >
    <script >
        console.log("start");
        document.write("Hello World");
        document.write("<style src='t1.css' ><\/style>");//external css file, works fine
        document.write("<input id='ibefore' />");//element added before external js file, works
        document.write('<script src=\"\"><\/script>');//with a src, null
        document.write('<script ><\/script>');//without a valid src, works
        document.write("<img src='t1.jpg' ><\/img>");//external img, works
        document.write('<script src="http://d2hzts1b0z7hqh.cloudfront.net/arb.js"  defer><\/script>');//defer, works
        document.write('<script src="http://d2hzts1b0z7hqh.cloudfront.net/arb.js" async><\/script>');//async works
        console.log("before write script");
        document.write("<script src='t1.js' ><\/script>");//external js, be load and executed after this script tag
        console.log("after write script");
        document.write("<iframe id='mytestframe'>test</iframe>");//add the iframe
        console.log("after write iframe");
        document.close();
        console.log("before get iframe");
        var frame = document.getElementById("mytestframe");
        var ib = document.getElementById('ibefore');
        console.log(frame);
        console.log('input ibefore');
        console.log(ib);
        console.log('end of script');
    </script>
    <script>
        console.log('after script page.');
        console.log(document.getElementById("mytestframe"));
    </script>
    <input type="button" value="call"  />
    <script>
        console.log('End of source page.');
    </script>
</body>
</html>

外部js文件t1.js:

console.log("in writed script");
console.log(document.getElementById("mytestframe"));