Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

html - Why Do Developers Split Up <script in JavaScript?

I see so many things like this: S = "<scr" + "ipt language="JavaScript1.2"> <!-- ";

Why do they do this, is there an application/browser that messes up if you just use straight "<script>"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...