JavaScriptHard
When would you use document.write()?
By FrontendPro Editorial Team Updated 9/26/2026
#JavaScript
Answer
In practice: never in new code. It exists for compatibility, and every use has a better replacement.
js
document.write('<p>Hello</p>'); // during parsing: inserts here
// after load: WIPES the entire document first
Why it is bad
- It destroys the page if called after load.
document.writeopens an implicitdocument.open()on a closed document, which clears everything — your DOM, your listeners, your state. - It blocks the parser. The browser must stop, parse the injected string, and cannot use its speculative preload scanner past that point. Chrome outright refuses
document.writeof a blocking script from a third-party origin on a slow connection. - It is a string, so it is an XSS hole the moment any user input reaches it.
- It does nothing in XHTML or in a document served as XML.
What to use instead
js
el.textContent = value; // text
el.append(node); // nodes
el.insertAdjacentHTML('beforeend', trusted); // trusted markup only
const t = document.querySelector('template'); // reusable fragments
To inject a script, create the element:
js
const s = document.createElement('script');
s.src = url; s.async = true;
document.head.append(s);
The honest answer to "when"
Two places you still see it legitimately: older third-party ad and analytics snippets that must run synchronously during parse, and a throwaway one-liner in the console or a codepen. In an interview it is fine to say you know what it does and that you would not ship it.
