JavaScript

js/document-write

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

umiarkowanastatycznefe-javascript

Dlaczego

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.

Poprawka

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.

Przykłady

// 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)

Źródła

Fakty

Identyfikator
js/document-write
Waga
umiarkowana
Sprawdzanie
statyczne sprawdzane w kodzie źródłowym przez audit
Dotyczy plików
jsx html vue svelte astro
Uczy jej skill
fe-javascript JavaScript in the browser
Od wersji
0.1.0

Plik reguły na GitHubie

Przeczytaj w terminalu

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