Why do old scripts use document.write, and what replaces it?
Old scripts use document.write() because it was the simplest way to put content into a page while it loaded: one line, no element to find. It is now deprecated. Replace it with DOM methods: textContent or createElement() plus append() for content, a <template> for larger blocks, and a <script> element with async or defer for loading other scripts.
Cite
CodeLifter Forum, "Why do old scripts use document.write, and what replaces it?", https://codelifter.com/forum/posts/why-do-old-scripts-use-documentwrite-and-what-replaces-it/, accessed 2026-11-30.- CodeLifter editorsStaffStaff, CodeLifter ·
What does document.write actually do?
document.write()hands a string of markup to the browser's HTML parser at the point where the parser currently is. Called from an inline<script>while the page is still loading, the text appears right where the script tag sits. That is why tutorials used it for everything from "last updated" dates to whole navigation menus and ad tags: the snippet worked wherever you pasted it.MDN's document.write() reference, last updated on 12 October 2026 when read, marks the method deprecated, says its use "is strongly discouraged", and quotes the HTML standard itself: "This method has very idiosyncratic behavior." The standard lists the cases. It can change the parser's state mid-page, "resulting in a DOM that does not correspond to the source of the document". It can clear the page "as if
document.open()had been called". It can be ignored or throw. And its exact behaviour "can in some cases be dependent on network latency."Why is it a problem now?
Situation What happens Source Inline <script>while the page loadsWrites at that point in the page MDN, Document.write Called after the page has loaded, for example in a click handler Calls document.open()first, which clears the pageMDN, Document.write Called from an asyncordeferscriptIgnored, with a console message MDN, Document.write Page served as XHTML ( application/xhtml+xml)Throws InvalidStateErrorMDN, Document.write Writes a third-party <script src>on a slow connection in ChromeThe script may not run at all Chrome intervention post Writes a string that came from user input or the URL Possible cross-site scripting MDN, Document.write The fifth row matters for performance. Chrome's post explains that when the parser meets a script it must stop and run it, and a script that writes another script tag makes it wait again for that download. Since Chrome 55, Chrome will not execute a
document.write()-inserted script when the user is on 2G and the write is in the top-level document, the script is parser-blocking, cross-site and not cached, and the page load is not a reload. The DevTools console warns about the pattern on any connection: "A Parser-blocking, cross-origin script ... is invoked via document.write()."The last row matters for security. MDN calls
document.write()an injection sink, the same class of API asinnerHTML; see the innerHTML thread for the general fix.What replaces each use?
Find what the call writes, then pick the matching replacement.
A bit of text, such as a date, a greeting or a counter. Put an empty element in the HTML where the text should go, give it an id, and set its
textContentfrom a script loaded withdefer:<p>Last updated: <span id="updated"></span></p>const el = document.getElementById("updated"); if (el) el.textContent = new Date(document.lastModified).toLocaleDateString();A few elements, such as a list of links. Build them with
document.createElement()and add them withappend(). MDN's append() page says strings passed to it "are inserted as equivalent Text nodes", so a title containing<stays text.A larger fixed block, such as a footer or a card layout. Put it in a
<template>and clone it. MDN's template element reference says the content "is not rendered" by default and is reached through thecontentproperty, aDocumentFragment; clone it withtemplate.content.cloneNode(true), fill in text withtextContent, thenappend()it.Another script, the common ad and widget pattern. Load it with a normal tag and
asyncordeferinstead of writing the tag:<script src="https://example.com/widget.js" async></script>. Chrome's post says scripts withasyncordeferare not affected by the intervention, and suggests adding the script element "with DOM API's likedocument.appendChild()" when it must be created from code. If the vendor's snippet still containsdocument.write(), ask the vendor for an asynchronous version; addingasyncto a snippet that writes will just get the write ignored.Static markup that never changes. Delete the script and type the HTML into the page. A surprising number of old snippets wrote content that could simply have been in the file.
Before and after
An example written for this answer, of a pattern common in old snippets:
<script> document.write("<a href='" + location.href + "'>Bookmark this page</a>"); </script>It builds HTML by joining strings around the page address with no escaping, which is the injection-sink pattern MDN warns about, and it only works while the page is still loading. In the replacement the link text is plain HTML, and the script only sets the address, as a property rather than a string of markup:
<a id="permalink" href="/">Link to this page</a> <script src="/js/permalink.js" defer></script>with
js/permalink.jscontainingdocument.getElementById("permalink").href = location.href;. Settinghrefas a property keeps the value as data, whatever characters it contains, and the link still works, pointing at the home page, if the script never runs.How do you find every document.write in a project?
Search the code, including inline scripts in your HTML:
grep -rn "document\.write" --include="*.html" --include="*.js" .Then open each page with the developer tools console visible and look for the ignored-call message from MDN's description and Chrome's parser-blocking warning. The modernising thread covers the other changes worth making while you have the file open, and the old scripts thread has a quick test page setup. The Script Shelf lists which old CodeLifter scripts were rewritten and how.
Short version
document.write()was popular because it wrote content exactly where the script tag sat.- It is deprecated: it can clear the page, be ignored in
asyncordeferscripts, and block or lose third-party scripts. - Use
textContentfor text,createElement()andappend()for elements,<template>for blocks. - Load other scripts with a
<script>tag andasyncordefer, not by writing the tag. - Search with
grep -rn "document\.write"and check the console.
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.
1 answer
- CodeLifter editorsStaffStaff, CodeLifter ·
Why does document.write erase my whole page? Because it was called after the page finished loading. MDN's document.write() reference explains that calling it on a "closed (loaded) document" automatically calls
document.open(), "which will clear the document." MDN's document.open() page lists what that means: "All existing nodes are removed from the document", and all event listeners registered on the document, its nodes or its window "are removed." So the page goes blank and every other script on it stops responding.The usual cause in an old snippet is a write that moved. It worked when it sat in an inline
<script>in the body, then someone put it inside awindow.onloadfunction, a click handler or asetTimeout, and now it runs after loading. Moving the script into a file withdeferdoes not help: MDN says writes from deferred or asynchronous scripts are ignored, with a console message, so the content simply never appears.The fix is the same in each case: write into an element that already exists, with
textContentorappend(), as in steps 1 and 2 of the opening post.