Why is the script tag broken up in to two strings? [duplicate]
-
30-06-2021 - |
Question
Possible Duplicate:
Why split the <script> tag when writing it with document.write()?
Looking at the enyo source, I see this (in enyo.js):
document.write('<scri' + 'pt src="' + root + "/source/boot/" + inSrc + '"></scri' + 'pt>');
Why is the <script
tag broken into <scri + pt
? The same is done for the end tag. Is this a secret of the Javascript ninja that I'm not aware of?
Solution
When a browser's html parser sees the string "</script>
", regardless of whether it is in a javascript string or not, it sees it as a closing script tag and ends the current script block. Breaking the "</script>
" tag into two pieces prevents this from happening when you need it as a javascript string.
See this explanation:
the tag is content-agnostic. Which means the HTML Parser doesn’t know we’re in the middle of a JavaScript string.
The processing of JavaScript doesn’t happen until after the browser has understood which parts are JavaScript. Until it sees that close tag, it doesn’t care what’s inside – quoted or not.
OTHER TIPS
it is designed to get the script tag around various filters.
To prevent browsers from blocking the document.write
. It's usually unsafe to do things of this sort.
Also, for old browsers which when seeing </script>
anywhere in the body, would stop execution right away. Which meant anything after the document.write
wouldn't be considered JavaScript code.
See this fiddle to see what I mean. The script
tag closes right after the alert.
This is necessary because the parser considers that substring as the closing <script>
tag in which the statement itself is contained, so it's necessary make a split somewhere in the middle