且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么要拆分 <script>用 document.write() 编写时标记?

更新时间:2023-09-29 22:32:34

</script> 必须分解,否则会结束封闭的 过早阻塞.实际上它应该在 </ 之间分开,因为脚本块(根据 SGML)应该是 由任何结束标签开放 (ETAGO) 序列终止(即 </):

</script> has to be broken up because otherwise it would end the enclosing <script></script> block too early. Really it should be split between the < and the /, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </):

尽管 STYLE 和 SCRIPT 元素使用 CDATA 作为其数据模型,但对于这些元素,用户代理必须以不同方式处理 CDATA.标记和实体必须被视为原始文本并按原样传递给应用程序.字符序列</"(结束标记打开分隔符)的第一次出现被视为终止元素内容的结尾.在有效文档中,这将是元素的结束标记.

Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.

但实际上浏览器只在实际的 </script> 关闭标记上解析 CDATA 脚本块.

However in practice browsers only end parsing a CDATA script block on an actual </script> close-tag.

在 XHTML 中没有对脚本块进行这种特殊处理,因此其中的任何 <(或 &)字符都必须是 &escaped; 就像在任何其他元素中一样.但是,将 XHTML 解析为老式 HTML 的浏览器会感到困惑.有一些涉及 CDATA 块的解决方法,但最简单的方法是避免使用未转义的这些字符.从适用于任一类型解析器的脚本编写脚本元素的更好方法是:

In XHTML there is no such special handling for script blocks, so any < (or &) character inside them must be &escaped; like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:

<script type="text/javascript">
    document.write('x3Cscript type="text/javascript" src="foo.js">x3C/script>');
</script>