Skip to content

Why document.write is slow and how to replace it

Best practices1 min readFixes check no-document-write

document.write blocks parsing and Chrome may ignore it on slow connections. Insert elements with DOM methods instead.

Step by step, with screenshots: Console errors and deprecated APIs: what the report flags →

Check your own site

Runs this check and the other 192, free, in about 45 seconds.

What it is

document.write() is an old JavaScript method that inserts HTML into the page at the exact point where the parser is, most often used by ad tags and widgets to add another script. While it runs, the browser stops building the page and waits.

When document.write inserts a script from another domain, the browser has to download and run it before it can continue, which delays everything below it. Since 2016 Chrome refuses to run such scripts for users on slow 2G-type connections, so the ad or widget simply does not appear for them.

OK looks like this: no document.write calls; scripts are added with async or defer attributes or appended with DOM methods such as appendChild. getReport counts the calls it sees while the page loads.

What a passing site looks like

  • document.write() is not usedwarning · −1 ptseffort M

document.write() usage

Why it matters. document.write blocks the page until the injected script arrives, and Chrome drops such scripts on slow connections, so the ad or widget simply does not appear.

How to fix it.
  1. Replace document.write with a normal <script async> tag or by appending the element from JavaScript.
  2. Update the ad or widget snippet; most vendors now provide an async version.

Questions people ask

What is document.write in JavaScript?

document.write() is a method that writes a string of HTML directly into the document while it is being parsed. It dates from the earliest days of JavaScript. Called after the page has loaded, it wipes the whole page, which is one reason modern code never uses it.

Why is document.write bad?

It blocks the HTML parser: the browser must pause, run the write and, for an injected external script, download and execute that script before building the rest of the page. That slows loading, and Chrome skips such scripts on slow connections, so the feature silently fails for some visitors.

What can you use instead of document.write?

Add scripts with a normal <script src="…" async> or defer tag in the HTML, or create them with document.createElement('script') and appendChild. For content, insert elements with DOM methods or insertAdjacentHTML. For ad and widget snippets, use the vendor's current async version.

Filed under Best practices. Copy is generated from the same catalogue that scores every report, so what you read here is what the report says.