document.write知多少

document.write知多少

原生JavaScript的API里document.write绝对是重量级的。如果大家对他的使用场景、注意事项、原理等不明晰,欢迎阅读本文。

使用场景

  1. 第三方合作

    1
    2
    3
    4
    5
    6
    <div id="third">
    <!--如果是A合作方需要插入iframe-->
    iframe
    <!--如果是B合作方需要插入ul-->
    ul[列表内容]
    </div>

    如果这段代码放在前端处理,不使用后端模板,用document.write可以轻松实现,当然实现的方式很多种,这里只是说明document.write可以胜任。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <div id="third">
    <script>
    if(A){
    document.write('iframe')
    }
    if(B){
    document.write('ul')
    }
    </script>

    </div>
  2. 广告

    一般广告代码中都是使用document.write来加载第三方广告,比如百度联盟的广告。通常都是这样用。

    1
    2
    3
    4
    <div id="ad">
    <!--corp.js会使用document.write将广告输出到这个位置-->
    <script src="http://baidu.com/corp.js">
    </div>

注意事项

如果看完了使用场合是不是觉得了解document.write了呢?其实不然,document.write的引入时机很重要。

还是看上述场景的案例,如果第一个不是内联的script,而是在js文件里写的呢?在js文件里的写法有2种,一种是DOMContentLoaded或onload之后使用write,好不疑问页面被清空了,另一种则是直接执行的write,具体write的内容在页面处于什么位置要取决于这个js引入的位置。

第二个案例,如果js是异步引入的(加async或者动态加入的),里面的document.write因安全原因是无法工作的。

Failed to execute ‘write’ on ‘Document’: It isn’t possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

工作原理

在弄清楚write的原理之前我们先看几种写法。

  • head中

    1
    2
    3
    4
    5
    6
    7
    <head>
    <meta charset="UTF-8">
    <script type="text/javascript">
    document.write('<p>test</p>')
    </script>

    </head>
    <!--请问上述代码在HTML中的什么位置?-->
  • body中

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <div id="test">
    <script type="text/javascript">
    <!-- 直接写 -->
    document.write('hello world');
    <!-- 子节点 -->
    var s=document.createElement('script');
    s.text='document.write("c")'
    document.getElementById('test').appendChild(s)
    </script>

    </div>
    <!-- 请问这两种写法的结果分别是什么?有区别吗? -->
  • 同步js

    1
    2
    <script src="http://cucygh.github.io/post.js" charset="utf-8"></script>
    <!-- 脚本中有write操作,输出的内容在什么位置?-->
  • 异步js

    1
    2
    <script src="http://cucygh.github.io/post.js" async charset="utf-8"></script>
    <!-- 脚本中有write操作,是否能正常输出,如果不能,有什么好的办法?-->

    接下来我们看下document.write的工作原理。

    页面在loading状态,按照自上而下的顺序依次解析script,如果遇到write直接输出,所以放在head的write都是在body顶部展示的。

    页面在loaded状态,即使没有调用document.open,write操作也会自动调用document.open方法从而将页面清空了。有的同学说将document.open=function(){}是不是可以避免,结论是No。

    Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.

所以使用document.write一定要知道执行的时机。

疑问

如果在一个指定位置异步加载多家的广告代码,如何实现呢?想知道答案下回分解。