document.write知多少

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

使用场景

  1. 第三方合作

    iframe

    ul[列表内容]

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

    if(A){        document.write('iframe')    }    if(B){        document.write('ul')    }
  1. 广告

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

注意事项

如果看完了使用场合是不是觉得了解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的原理之前我们先看几种写法。

  1. head中

document.write('test
')

  1. body中

document.write('hello world');

var s=document.createElement('script');
s.text='document.write("c")'
document.getElementById('test').appendChild(s)

  1. 同步js

  2. 异步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一定要知道执行的时机。

疑问

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

关键字:JavaScript, css, html, document


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部