原生JavaScript的API里document.write绝对是重量级的。若是你们对他的使用场景、注意事项、原理等不明晰,欢迎阅读本文。
第三方合做javascript
<div id="third"> <!--若是是A合做方须要插入iframe--> iframe <!--若是是B合做方须要插入ul--> ul[列表内容] </div>
若是这段代码放在前端处理,不使用后端模板,用document.write能够轻松实现,固然实现的方式不少种,这里只是说明document.write能够胜任。html
<div id="third"> <script> if(A){ document.write('iframe') } if(B){ document.write('ul') } </script> </div>
广告前端
通常广告代码中都是使用document.write来加载第三方广告,好比百度联盟的广告。一般都是这样用。java
<div id="ad"> <!--corp.js会使用document.write将广告输出到这个位置--> <script src="http://baidu.com/corp.js"> </div>
若是看完了使用场合是否是以为了解document.write了呢?其实否则,document.write的引入时机很重要。git
仍是看上述场景的案例,若是第一个不是内联的script,而是在js文件里写的呢?在js文件里的写法有2种,一种是DOMContentLoaded或onload以后使用write,好不疑问页面被清空了,另外一种则是直接执行的write,具体write的内容在页面处于什么位置要取决于这个js引入的位置。github
第二个案例,若是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的原理以前咱们先看几种写法。app
head中less
<head> <meta charset="UTF-8"> <script type="text/javascript"> document.write('<p>test</p>') </script> </head> <!--请问上述代码在HTML中的什么位置?-->
body中
<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
<script src="http://cucygh.github.io/post.js" charset="utf-8"></script> <!-- 脚本中有write操做,输出的内容在什么位置?-->
异步js
<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,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必定要知道执行的时机。
若是在一个指定位置异步加载多家的广告代码,如何实现呢?想知道答案下回分解。