为什么不使用document.write? [英] Why not document.write?

查看:63
本文介绍了为什么不使用document.write?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在Javascript中使用 document.write 通常不被认为是一种好习惯?我知道这不是最优雅或最好的方法,但是它有任何真正的错误吗?可以吗?在什么情况下,它会比 inner.HTML

我知道,如果在加载后使用它,它将重写文档.但是,即使我试图重写文档,也应该使用 innerHTML 吗?如果是这样,为什么?

我知道有人问过我是否在发布之前查看过相关问题;我做到了但是我没有发现任何令人满意的东西.

解决方案

正确使用 可以,但是使用范围非常有限.

无法在XHTML中使用它,但是我除非您有非常非常好的理由,否则建议不要使用XHTML.

在初始页面加载完成后调用 document.write 时,就会出现问题.页面加载正常,但随后会导致隐式的 document.open ,该文件会从窗口中清除文档并重新开始.

使用 document.write 也意味着您无法要求加载脚本或使用 解决方案

When used correctly, it's fine, but of very limited use.

You can't use it in XHTML, but I would recommend not using XHTML anyway unless you have a really, really good reason to.

The problem comes when you call document.write after the initial page load is complete. During page load is fine, but afterward, it causes an implicit document.open, which clears the document from the window and starts fresh.

Using document.write also means you can't demand-load your scripts or use the async or defer attributes on your script elements.

Finally, I usually recommend putting your JavaScript in a separate (single) JavaScript file at the very end of the document (just before the closing </body> tag). If you want to use document.write to output to the page, you'd have to include that script file higher up or use code directly within the HTML, neither both of which I recommend against.

So since it's of such limited use compared with other methods, it's best to get proficient with the other methods.

这篇关于为什么不使用document.write?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆