[英]Why Do Developers Split Up <script in JavaScript?
I see so many things like this: S = "<scr" + "ipt language=\\"JavaScript1.2\\">\\n<!--\\n";
我看到很多这样的东西: S = "<scr" + "ipt language=\\"JavaScript1.2\\">\\n<!--\\n";
Why do they do this, is there an application/browser that messes up if you just use straight "<script>"
?他们为什么这样做,如果您直接使用"<script>"
,是否有应用程序/浏览器会搞砸?
Have a look at this question:看看这个问题:
Javascript external script loading strangeness. Javascript 外部脚本加载奇怪。
Taken from bobince's answer :取自bobince 的回答:
To see the problem, look at that top line in its script element:要查看问题,请查看其脚本元素中的第一行:
<script type="text/javascript"> document.write('<script src="set1.aspx?v=1234" type="text/javascript"></script>'); </script>
So an HTML parser comes along and sees the opening <script> tag.因此,一个 HTML 解析器出现并看到了开始的 <script> 标记。 Inside <script>, normal <tag> parsing is disabled (in SGML terms, the element has CDATA content).在 <script> 中,正常的 <tag> 解析被禁用(在 SGML 术语中,元素具有 CDATA 内容)。 To find where the script block ends, the HTML parser looks for the matching close-tag </script>.为了找到脚本块的结束位置,HTML 解析器会查找匹配的关闭标签 </script>。
The first one it finds is the one inside the string literal.它找到的第一个是字符串文字中的那个。 An HTML parser can't know that it's inside a string literal, because HTML parsers don't know anything about JavaScript syntax, they only know about CDATA. HTML 解析器无法知道它在字符串文字中,因为 HTML 解析器对 JavaScript 语法一无所知,它们只知道 CDATA。 So what you are actually saying is:所以你说的其实是:
<script type="text/javascript"> document.write('<script src="set1.aspx?v=1234" type="text/javascript"> </script>
That is, an unclosed string literal and an unfinished function call.也就是说,一个未闭合的字符串文字和一个未完成的函数调用。 These result in JavaScript errors and the desired script tag is never written.这些会导致 JavaScript 错误,并且永远不会写入所需的脚本标记。
A common attempt to solve the problem is:解决问题的常见尝试是:
document.write('...</scr' + 'ipt>');
This wouldn't explain why it's done in the start tag though.这并不能解释为什么它在开始标签中完成。
The more appropriate way to append scripts is to use the DOM.附加脚本更合适的方法是使用 DOM。
<script>
.创建一个<script>
类型的元素。 See documentation for document.createElement
.请参阅 document.createElement 的document.createElement
。src
, type
etc.)设置其属性( src
、 type
等)body.appendChild
to add this to the DOM.使用body.appendChild
将其添加到 DOM。This is a much cleaner approach.这是一种更清洁的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.