antipatternperformance

document-write

When this policy is disabled, the APIs document.write, document.writeln, document.open and document.close will thow a DOMException when used. These APIs have been around since the very early days of the web and using them is a bad idea because they dynamically rewrite your HTML markup and block parsing of the document.

How to apply this policy

Send the following HTTP header to control the document-write policy, and disallow it on all origins:

Feature-Policy: document-write 'none'

Affected use case example

HTML

<p>Existing content</p>

JavaScript

window.addEventListener('load', () => {
        document.write('<p>New content</p>');
        if (document.body.innerText.includes('New content')) {
          DemoUtils.reportDemoResult(true);
        } else {
          throw new Error('DOM does not contain the expected new content');
        }
      });

Output

Loading...

Waiting for the demo to report a result...

Does it work?

Currently Firefox, and Chromium based browsers, such as Google Chrome, Samsung Internet, and Opera, are the only user-agents to support Feature Policy. The minimum version that correctly recognises the document-write policy is:

Mozilla Firefox

Unknown

Google Chrome

74+

Microsoft Edge

Not supported

Apple Safari

Not supported

Discussion