avoid-using-document.write()-in-javascript

“`html

Initially, document.write() was the favored technique for inserting content into a web page. It was quick, straightforward, and beneficial for novice developers. However, as websites became more sophisticated, our approach to building them has evolved. Nowadays, employing document.write() is regarded as unwise due to several valid reasons. In this post, you will discover the reasons why document.write() is viewed as a harmful practice in JavaScript.

Contents:

What is document.write()?

In basic terms, document.write() is employed to write a string of text straight onto the web page.

Syntax:

document.write("<h1>Hello, From Intellipaat!</h1>");

When the browser encounters this line of code, it inserts the HTML content into the document while the code is being processed.

Real-World Example of the Issue

For an extended period, advertising companies relied on document.write() to place ads on websites. However, this caused pages to load slowly, display blank areas while waiting for the ad, or even lead the site to crash on slower devices. Nowadays, the majority of advertising companies utilize improved and safer approaches, like iframes or specialized JavaScript tools, to display ads without creating these issues.

Why is document.write() a Poor Practice Today?

Modern websites are expected to be fast, secure, and user-friendly. However, document.write() contradicts all these objectives. Let’s examine each one in detail:

1. It obstructs page rendering

When the browser comes across document.write(), it halts everything such as parsing HTML, fetching stylesheets, and executing JavaScript. This results in slower site performance, especially on mobile devices or those with sluggish internet connections.

2. Not ideal for Async Scripts

Currently, most JavaScript code is loaded asynchronously to prevent page blocking. The document.write() method compels the browser to pause, contradicting the purpose of these performance-enhancing strategies.

3. It Disrupts Your Page After Load

One significant reason to avoid document.write() is that if it is executed after the page has loaded, such as through the window.onload() function, it will wipe the entire document and replace it with new content.

4. It Introduces Security Vulnerabilities

Using document.write() to insert user-generated content exposes you to Cross-Site Scripting attacks. A malicious user can inject a script and access all data from your website’s users.

Contemporary Alternatives to document.write()

Using document.write() in your scripts is not advisable, but there are superior and safer methods for adding content dynamically. Let’s explore a few:

1. Utilize innerHTML

innerHTML is a property that enables you to alter the HTML content within an element. It can be used to add text, HTML tags, or both to a specific section of your webpage.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>innerHTML</title>
</head>
<body>
    <div id="text"></div>
    <script>
        document.getElementById('text').innerHTML = '<h1>Hello From Intellipaat!</h1>'
    </script>
</body>
</html>

Output:

Use innerHTML Output

Explanation: In this illustration, the <div> with the id “text” will now feature an <h1> header that reads “Hello From Intellipaat”.

2. Employ DOM Methods

Rather than using innerHTML to insert HTML content into the webpage, you can also utilize DOM Methods, which allow you to construct and manipulate elements securely.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM methods</title>
</head>

<body>
    <script>
        const h1 = document.createElement("h1");       
        h1.textContent = "Hello From Intellipaat!";
        document.body.appendChild(h1);   
    </script>
</body>
</html>

Output:


“““html
Use DOM Methods Output

Clarification: In this case, an h1 element is generated with the text “Greetings from Intellipaat!” utilizing the DOM technique, and appended to the end of the body.

Summary

Although document.write() offers a rapid method to insert content into a web page, it is seldom employed in projects today due to multiple drawbacks such as diminishing site speed, inducing unexpected behaviors on your website, and posing security threats. Contemporary websites are designed to be fast, engaging, and secure, with various superior alternatives available for similar tasks, such as innerHTML or applying DOM techniques. If you are utilizing document.write() in your scripts, it’s time to make a switch.

Why is document.write() Viewed as a Poor Practice in JavaScript – FAQs

1. Why isn’t document write used in JavaScript?

Currently, using document.write() for adding dynamic content to a webpage is not advisable because it hinders page loading, decreases performance, and could clear your content if invoked after the page loads.

2. What does document.write() accomplish in JavaScript?

document.write() is intended to insert text or HTML directly into a webpage while it’s being loaded. If invoked for displaying content post-page reload, it will remove all existing data.

3. Is document.write() obsolete?

No, it’s not formally labeled as obsolete, yet it’s highly discouraged and regarded as a poor practice.

4. What is the role of a document in JavaScript?

The document object signifies the complete webpage. It enables you to access and modify HTML elements using JavaScript.

5. What is the expanded form of DOM?

DOM refers to Document Object Model. It is a hierarchical structure created by your browser for every website loaded, facilitating JavaScript in altering and organizing the content of a webpage.

The post Avoid Using document.write() in JavaScript appeared first on Intellipaat Blog.

“`


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This