原生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必定要知道執行的時機。
若是在一個指定位置異步加載多家的廣告代碼,如何實現呢?想知道答案下回分解。