Home > Web Front-end > JS Tutorial > Why Split `` Tags Using `document.write()`?

Why Split `` Tags Using `document.write()`?

DDD
Release: 2024-12-11 17:10:10
Original
871 people have browsed it

Why Split `` Tags Using `document.write()`?

Document.write() Script Tag Splitting: A Rationale

In web development, it's not uncommon to encounter scripts written using document.write() that split the <script> or /script> tags. This practice may raise the question, "Why employ such a technique?"</p> <p><strong>Reason for Splitting:</strong></p> <p>The answer lies in the way HTML parsers handle CDATA sections within <script> elements. While SGML dictates that a <script> block should terminate upon encountering any end-tag open sequence (e.g., </), browsers only recognize an actual </script> close-tag as the end of a script block.

Significance of Splitting:

Consider the following example:

<script type='text/javascript'>
  document.write('<scr' + 'ipt type="text/javascript" src="script.js"></sc' + 'ript>');
</script>
Copy after login

In this case, if the <script> tag were not split, the close-tag sequence </sc would be interpreted as the end of the enclosing <script> block, prematurely terminating the script. Splitting the tag ensures that the browser correctly parses and executes the entire script.</p> <p><strong>XHTML and Script Writing:</strong></p> <p>In XHTML, there is no special handling for script blocks. Characters such as < and & must be escaped within scripts. However, using unescaped characters can lead to confusion in browsers parsing XHTML as HTML.</p><p><strong>Alternative Script Writing:</strong></p><p>To cater to both XHTML and HTML parsers, consider using the following approach:</p><pre class="brush:php;toolbar:false"><script type="text/javascript"> document.write('\x3Cscript type="text/javascript" src="script.js"></script>');

By escaping the characters using hexadecimal notation, you ensure that the script will be correctly interpreted by all parsers.

The above is the detailed content of Why Split `` Tags Using `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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template