Document.write() and Script Tag Splitting: Why It's Done
When using the document.write() method to create a script tag, you may notice that some websites separate the <script> and </script> tags across multiple calls. This technique is employed for a specific reason: to avoid premature termination of the script block.
Browsers typically parse HTML using SGML rules. According to SGML, script blocks should end on any end-tag open (ETAGO) sequence, such as <[/). However, in practice, browsers only end parsing a CDATA script block on a proper close tag.
Therefore, including the full <script> and </script> tags within a single document.write() call would cause the browser to end the script block prematurely upon encountering the
To prevent this issue, splitting the tags ensures that the browser correctly interprets and executes the script. The split can be between < and /, allowing the script block to be properly terminated only when the full sequence is written.
A better alternative to using this splitting technique is to escape any < or & characters within the script and create the script element as follows:
document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');This approach works for both HTML5 and XHTML documents, ensuring cross-compatibility and avoiding browser confusion.
The above is the detailed content of Why Do Some Websites Split `` and `` Tags with `document.write()`?. For more information, please follow other related articles on the PHP Chinese website!