document.write 知多少

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

使用场景

  1. 第三方合作

    iframe ul[列表内容]

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

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

  3. body中

  4. 同步js

    
    
  5. 异步js

    
    

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

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

    2. 页面在loaded状态,即使没有调用document.open,document.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一定要知道执行的时机。

    疑问

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