Home > Web Front-end > JS Tutorial > Why Do Some Websites Split `` and `` Tags with `document.write()`?

Why Do Some Websites Split `` and `` Tags with `document.write()`?

Patricia Arquette
Release: 2024-12-12 12:53:12
Original
635 people have browsed it

Why Do Some Websites Split `` and `` Tags with `document.write()`?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template