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 (), which includes the 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>
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!