6

Why does this javascript line looks like this? I mean, why there's an extra + near the end?

'<script type="text/javascript" src="' + src + '"></' + 'script>'

Source: http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/base.js#511

Marcin
  • 145
  • 5

1 Answers1

10

Because if you have "</script>" inside of a <script> tag, the browser will think you have closed your script tag. It's a pretty common way to include the text </script> inside of a string within <script> tags.

James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • Why wouldn't '' work? – Terry Jan 17 '12 at 20:52
  • 2
    Note that this little trick has no benefit at all if you load the script as an external file. So it's "just in case"... – user123444555621 Jan 17 '12 at 20:56
  • 2
    @Terry: Because the HTML parser needs to find the contents of the ``. Only after that are the contents passed to the JS engine for further processing. The HTML parser is not aware of JavaScript syntax, so it doesn't know wether or not the end tag is inside a string literal. – user123444555621 Jan 17 '12 at 21:01
  • @Pumbaa80: Thank you. I'm going to have to think about that a bit, maybe play with it a little. The combination of html and Javascript is indeed interesting. It was all so much simpler back in the days of Fortran, but, hey, onward and upward! – Terry Jan 17 '12 at 22:00
  • 2
    The other way you see it done is `...<\/script>`, since JavaScript sees `\/` as a slash, but the HTML parser doesn't. – T.J. Crowder Jan 17 '12 at 22:29