Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptWhy split the tag when writing it within document.write() method in...

Why split the tag when writing it within document.write() method in JavaScript ?

The code within the script tag is executed when the browser processes the tag. The document.write() method is used to delete all the existing content from the HTML document and inserts the new content specified within document.write() method. However, before the browser loads a page it builds the DOM tree by parsing the HTML markup. Whenever a script tag is encountered it must be executed before proceeding with the process of parsing. The script tag is split when used within document.write() method because while parsing the HTML parser on seeing the “</”” of the script tag inside the document.write() considers it to be the closing tag for the script tag within which the document.write() is enclosed. This results in incomplete execution of the contents in the outer script tags. In modern days, use of document.write() method is highly discouraged as it causes performance issues and may not work at all in certain cases.

Note: This procedure have been used to include jQuery files only.

Below examples implements the above approach:

Example 1: In this example, we will use <script> inside the document.write without splitting the tag.




<!DOCTYPE html> 
<html
  
<head
    <style
        body { 
            text-align:center; 
        
        h1 { 
            color:green; 
        
    </style
</head
  
<body
    <h1>neveropen</h1>
      
    <script
        document.write(
        "<script><h1>neveropen!</h1></script>"); 
          
        document.write(
        "<p>A computer science portal for neveropen</p>") 
    </script
</body
  
</html>


Output:

Example 2: In this example we will use <script> inside the document.write by splitting the tag.




<!DOCTYPE html> 
<html
  
<head
    <style
        body { 
            text-align:center; 
        
        h1 { 
            color:green; 
        
    </style
</head
  
<body
    <h1>neveropen</h1>
      
    <script
        document.write(
        "<script><h1>neveropen!</h1></scr"+"ipt>"); 
          
        document.write(
        "A computer science portal for neveropen"); 
    </script
</body
  
</html>


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments