Skip to content
CodeLifter
Search/ Browse prompts
CodeLifter Forum

Why do old scripts use document.write, and what replaces it?

Staff answerWritten by CodeLifter editors · Script Shelf1 replyupdated

Short answer

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.

Written by CodeLifter editors · Staff, CodeLifter ·
CiteCodeLifter 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.
  1. Staff, 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 loads Writes 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 page MDN, Document.write
    Called from an async or defer script Ignored, with a console message MDN, Document.write
    Page served as XHTML (application/xhtml+xml) Throws InvalidStateError MDN, Document.write
    Writes a third-party <script src> on a slow connection in Chrome The 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 as innerHTML; see the innerHTML thread for the general fix.

    What replaces each use?

    Find what the call writes, then pick the matching replacement.

    1. 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 textContent from a script loaded with defer:

      <p>Last updated: <span id="updated"></span></p>
      
      const el = document.getElementById("updated");
      if (el) el.textContent = new Date(document.lastModified).toLocaleDateString();
      
    2. A few elements, such as a list of links. Build them with document.createElement() and add them with append(). MDN's append() page says strings passed to it "are inserted as equivalent Text nodes", so a title containing < stays text.

    3. 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 the content property, a DocumentFragment; clone it with template.content.cloneNode(true), fill in text with textContent, then append() it.

    4. Another script, the common ad and widget pattern. Load it with a normal tag and async or defer instead of writing the tag: <script src="https://example.com/widget.js" async></script>. Chrome's post says scripts with async or defer are not affected by the intervention, and suggests adding the script element "with DOM API's like document.appendChild()" when it must be created from code. If the vendor's snippet still contains document.write(), ask the vendor for an asynchronous version; adding async to a snippet that writes will just get the write ignored.

    5. 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.js containing document.getElementById("permalink").href = location.href;. Setting href as 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 async or defer scripts, and block or lose third-party scripts.
    • Use textContent for text, createElement() and append() for elements, <template> for blocks.
    • Load other scripts with a <script> tag and async or defer, not by writing the tag.
    • Search with grep -rn "document\.write" and check the console.
    2
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

  1. 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 a window.onload function, a click handler or a setTimeout, and now it runs after loading. Moving the script into a file with defer does 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 textContent or append(), as in steps 1 and 2 of the opening post.

CodeLifter Forum. Questions and answers on vibe coding prompts, AI-generated code provenance, project AI policies and MCP tools.