JavaScript

js/document-write

Never insert content with document.write; create elements or load scripts with the DOM.

moderatestaticfe-javascript

Why

document.write blocks the HTML parser while it runs; a script written with it must download before the page can continue, and Chrome may refuse to run such a script on slow connections. Called after the page has loaded, it wipes the whole document. It also writes raw markup, so untrusted text becomes script.

Fix

Create elements (document.createElement, append, textContent) or use a <template>. Load a third-party script with <script async src> or by appending a script element.

Examples

// bad
document.write('<script src="https://example.com/widget.js"><\/script>')
// good
const script = Object.assign(document.createElement('script'), { src: 'https://example.com/widget.js', async: true })
document.head.append(script)

Sources

Facts

Id
js/document-write
Severity
moderate
Check
static checked in the source by audit
Applies to
jsx html vue svelte astro
Taught by the skill
fe-javascript JavaScript in the browser
Since version
0.1.0

Rule file on GitHub

Read it in the terminal

npx github:dawidolko/frontend-skills explain js/document-write