4

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>"?

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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...
Correctly means wrong in this case. Relying on such behavior makes it very difficult to write new HTML/Javascript renders.
Just doing <\/script> is enough
0

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

  1. Create an element of type <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.

1 Comment

Doesn't answer the question at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.