javascript - 为什么用 document.write() 写 <script> 标签时要拆分它?

标签 javascript html

为什么有些网站(或向客户提供 javascript 代码的广告商)采用拆分 <script> 的技术?和/或 </script>标记在 document.write() 内来电?

我注意到亚马逊也这样做,例如:

<script type='text/javascript'>
  if (typeof window['jQuery'] == 'undefined') document.write('<scr'+'ipt type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></sc'+'ript>');
</script>

最佳答案

</script>必须分解,否则它将结束封闭的<script></script>阻止太早。真的应该在 < 之间分开和 / , 因为脚本 block (根据 SGML)应该是 terminated by any end-tag open (ETAGO) sequence (i.e. </ ) :

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 脚本 block 。关闭标签。

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

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

关于javascript - 为什么用 document.write() 写 &lt;script&gt; 标签时要拆分它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/236073/

相关文章:

javascript - 如何将图像标题添加到 jQuery ImageViewer 插件中的事件项目?

javascript - AngularJS 和 Sanitize - 无需 ngBind 指令即可清理 HTML

javascript - Ajax 文件上传, 'progress' 上传事件不会在 Edge 浏览器中触发

javascript - 用 var 重新声明对象

html - 如何使用 Angular 将值绑定(bind)到 Web 组件的属性?

jquery - 隐藏div时如何设置背景颜色

php - 用于邮寄的最佳所见即所得编辑器(或用于邮寄的最佳使用方式)

javascript - Vue 的 'destroyed' 方法是否在页面刷新时调用?

javascript - 单击其子项时检测 div

html - 在 HTML 中使用 `pandoc-citeproc` 渲染引用书目