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

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

Barbara Streisand
Release: 2024-12-25 19:04:10
Original
757 people have browsed it

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

Splitting <script> Tags in document.write()</strong></p> <p>Splitting <script> and </script> tags using document.write() is a technique employed by some websites to dynamically add scripts to a webpage.

Why is Splitting Necessary?

In HTML, <script> tags enclose JavaScript code. When the browser encounters a <script> tag, it interprets the code within and executes it. However, if the <script> tag is split into two parts and written with document.write(), it prevents premature termination of the script block.</p> <p><strong>Browser Behavior with CDATA</strong></p> <p>In HTML, <script> tags use a CDATA (Character Data) section for their content. CDATA blocks are supposed to end when they encounter an end-tag open delimiter, such as <. However, browsers typically only terminate CDATA script blocks on an actual </script> close-tag.

Example

For instance, the following code from Amazon demonstrates the technique:

<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>
Copy after login

Alternative Approaches

In XHTML, scripts must be escaped to prevent confusion. A better approach is to use a hexadecimal character sequence to write the script element, as seen below:

<script type="text/javascript">
    document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>
Copy after login

By following these guidelines, developers can effectively incorporate dynamic scripts into their webpages while maintaining compatibility with different browsers and HTML standards.

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