-2

I'm trying to write some code in the <head> like this, but it doesn't work:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
    document.writeln('<script src="js/messages.js"></script>'); 
  </script>
</head>
<body>

<script>
</script>

</body>
</html>

It prints '); in the page and

<head>
  <script type="text/javascript">
    document.writeln('<script src="js/messages.js"></script>'); 
  </script>
</head>

in the code.

Hoconosc
  • 416
  • 9
  • 24

1 Answers1

2

The first </script> will end the script element in the middle of the string.

Your JavaScript will throw an error (because the string isn't terminated) and everything after it will be treated as text in the HTML document (which will get written to the body because you can't have text nodes as child elements of the head element in HTML).

You need to avoid having that sequence of characters in your JavaScript.

Escape the /

document.writeln('<script src="js/messages.js"><\/script>'); 
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • It works, but it writes `document.writeln('` – Hoconosc Dec 10 '14 at 14:11