views:

127

answers:

2

I see so many things like this: 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>"?

+6  A: 

Have a look at this question:

Javascript external script loading strangeness.

Taken from bobince's answer:

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. Inside <script>, normal <tag> parsing is disabled (in SGML terms, the element has CDATA content). To find where the script block ends, the HTML parser looks for the matching close-tag </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. 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.

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.

Georg
Of note, this hasn't been a problem since the days of Netscape. All modern browsers (including IE6 in this use of "modern") work "correctly" in this regard. Unfortunately the same can't be said for the syntax hiliters in some editors...
Charles
Correctly means wrong in this case. Relying on such behavior makes it _very_ difficult to write new HTML/Javascript renders.
Georg
A: 

The more appropriate way to append scripts is to use the DOM.

  1. Create an Element called "script". See documentation for document.createElement.
  2. Set its attributes (src, type etc.)
  3. Use body.appendChild to add this to the DOM.

This is a much cleaner approach.

amitbehere
Doesn't answer the question at all.
Georg