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

Why Split the `` Tag When Using `document.write()`?

Patricia Arquette
Release: 2024-12-14 08:02:11
Original
772 people have browsed it

Why Split the `` Tag When Using `document.write()`?

Splitting the <script> Tag in document.write()</strong></p> <p>Document.write() is a powerful method for dynamically inserting content into an HTML document. However, when writing a <script> tag using document.write(), it becomes necessary to split the tag into multiple parts. This technique is employed by various websites, including Amazon, to prevent premature termination of the <script> block.</p> <p>The need for splitting arises from the way browsers handle the </script> tag. In SGML, a script block is supposed to end on any end-tag open sequence ( tag. However, browsers only end parsing upon encountering an actual close-tag.

Therefore, if the is not split up, it will prematurely end the entire enclosing <script></script> block. To prevent this, websites split the tag around the < and /, preserving the required end-tag open sequence without prematurely ending the block.

For instance, Amazon uses this technique to dynamically include jQuery:

<script type='text/javascript'>
  if (typeof window['jQuery'] == 'undefined') document.write('<scr'+'ipt type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></sc'+'ript>');
</script></p>
<p>In XHTML, there is no special handling for script blocks, so all characters within them must be escaped. However, this can cause confusion for browsers parsing XHTML as HTML. To avoid this, it is preferable to use hexadecimal character references to represent the less than and ampersand characters:</p>
<pre class="brush:php;toolbar:false"><script type="text/javascript">
    document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>
Copy after login

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