为什么要拆分< script>使用document.write()写入时使用标记? [英] Why split the <script> tag when writing it with document.write()?

查看:89
本文介绍了为什么要拆分< script>使用document.write()写入时使用标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么有些网站(或给客户javascript代码的广告客户)采用了分割< script> 和/或< / script> 标记在 document.write()调用内

Why do some sites (or advertisers that give clients javascript code) employ a technique of splitting the <script> and/or </script> tags up within document.write() calls?

亚马逊也会这样做,例如:

I noticed that Amazon does this as well, for example:

<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> 块。真的,它应该被分割在< / 之间,因为假设一个脚本块(根据SGML)将终止于任何结束标记打开(ETAGO)序列(即<$
$ b

</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.

然而,在实践中,浏览器只能结束解析CDATA脚本块实际< / script> close-tag。

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>

这篇关于为什么要拆分&lt; script&gt;使用document.write()写入时使用标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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