Quiz

When would you use `document.write()`?

Topics
Web APIsJavaScriptHTML

TL;DR

Almost never in new application code. During HTML parsing, document.write() injects markup into the input stream; after the document has loaded, it can implicitly call document.open() and replace the page. Its behavior in deferred or asynchronous scripts is problematic, it is an injection sink for untrusted strings, and browsers may intervene in slow-network cases.

You may encounter it in legacy scripts or tightly controlled parser-time snippets. Replace it with normal HTML, DOM creation methods, or explicit script loading. Use the console and debugger—not document.write()—for debugging.


Why parser timing matters

This writes while the parser is processing the document:

<script>
document.write('<p>Inserted while parsing</p>');
</script>

The result depends on when and how the script executes. Calling it later is destructive:

window.addEventListener('load', () => {
// This can erase the existing document. Do not do this.
document.write('<p>Replacement document</p>');
});

Safer alternatives

For text or DOM elements, create and append nodes:

const heading = document.createElement('h1');
heading.textContent = 'Hello, world!';
document.querySelector('#content').append(heading);

For static content, put the markup in HTML. For optional scripts, create a <script> element or use dynamic import(). If HTML from users is intentionally supported, process it with an appropriate sanitizer; do not pass it to document.write() or innerHTML directly.

Maintaining legacy usage

First determine whether the third-party script requires parser-time synchronous insertion. Test the replacement under slow networks, restrictive CSP, and supported browsers. If the call cannot yet be removed, ensure every string is developer-controlled, isolate the integration, and do not call it after parsing.

Further reading

Exercises

Check your understanding
Beta
Check your understanding Exercise
Check your understanding Exercise

Which statements about document.write() are correct? Select all that apply.