[X]

The Split Script Tag

browser tricks 1997 still works

To write a script tag from inside a script, you had to break the closing tag in half, because the HTML parser could not tell code from markup.

In 2026: Still works, and still necessary, which is the joke. An HTML parser ends the current script the instant it sees the characters of a closing script tag, even inside a JavaScript string, so document.write of a script element must split the tag. Every ad tag, counter and analytics snippet of the era carried this, and it would still bite you today.

Where it came from: A consequence of HTML parsing, universal in inline scripts from the mid 1990s. Still required today. MDN

<p id="out"></p>

<script language="JavaScript">
// You cannot write "</scr" + "ipt>" as one piece. The parser would
// see the closing tag inside your string and end THIS script early.
var slot = document.getElementById("out");
var tag = "<scr" + "ipt>document.title='written from a string'</scr" + "ipt>";
slot.innerHTML = "This string builds a script tag without ending the current one:" +
                 "<br><code>" + tag.replace(/</g, "&lt;") + "</code>";
</script>
sandboxed demo · breaks nothing but itselfrestart

More in browser tricks

all 25 in browser tricks › · the whole library ›