Open In App

Why Split the <script> tag when Writing it within document.write() method in JavaScript?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In modern JavaScript development, the use of the document.write() method is discouraged due to its potential to cause performance issues and disrupt the parsing process of HTML.

When the browser encounters a <script> tag, it pauses the parsing of HTML to execute the code within the script. Using document.write() during this phase overwrites the entire page content, which can break the current page structure and lead to incomplete execution, particularly if there are script tags within the document.write() output.

As a result, better alternatives such as DOM manipulation methods should be used for dynamically modifying content.

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

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

html
<!DOCTYPE html> 
<html> 

<head> 
    <style> 
        body { 
            text-align:center; 
        } 
        h1 { 
            color:green; 
        } 
    </style> 
</head> 

<body> 
    <h1>GeeksforGeeks</h1>
    
    <script> 
        document.write(
        "<script><h1>GeeksforGeeks!</h1></script>"); 
        
        document.write(
        "<p>A computer science portal for geeks</p>") 
    </script> 
</body> 

</html>

Output:

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

html
<!DOCTYPE html> 
<html> 

<head> 
    <style> 
        body { 
            text-align:center; 
        } 
        h1 { 
            color:green; 
        } 
    </style> 
</head> 

<body> 
    <h1>GeeksforGeeks</h1>
    
    <script> 
        document.write(
        "<script><h1>GeeksforGeeks!</h1></scr"+"ipt>"); 
        
        document.write(
        "A computer science portal for geeks"); 
    </script> 
</body> 

</html>

Output:



Similar Reads