Back

Absence of document.write

What is the instruction document.write ?

It is a browser-native JavaScript method that dynamically writes HTML or JavaScript code directly into a page. When the page is fully loaded, it replaces the existing code with the defined one.

<html>
    ...
    <script>
        document.write("I replace the content of the page");
    </script>
</html>

Why should it be avoided ?

The use of document.write can delay the display of the page by several seconds. Moreover, in some cases (a slow connection for example) chrome blocks its use and makes the page rendering uncertain.

How to replace its use

When the instruction document.write is used in the JavaScript code of the page, it is necessary to remove or replace it with methods to manipulate the DOM.

For example, to insert HTML code :

<script>
    document.getElementById("container").innerHTML = "Properly added HTML content";
</script>

To dynamically integrate a JavaScript :

<script>
    var script = document.createElement('script'); 
    script.src = 'https://cdn.example.com/script.js'; 
    document.head.appendChild(script);
</script>

If a third party script uses document.write, contact the supplier to find an alternative solution.