in
Written by Harry Roberts on CSS Wizardry.
View this web page as Markdown.
Desk of Contents
Impartial writing is delivered to you by way of my fantastic
Supporters.
For those who’ve ever run a Lighthouse take a look at earlier than, there’s a excessive likelihood you’ve seen
the audit Keep away from
:
doc.write()

For customers on gradual connections, exterior scripts dynamically
injected by way ofdoc.write()can delay web page load by tens of
seconds.
You will have additionally seen that there’s little or no clarification as to why
doc.write() is so dangerous. Nicely, the brief reply is:
From a purely performance-facing viewpoint, doc.write() itself
isn’t that particular or distinctive. In actual fact, all it does is surfaces potential
behaviours already current in any synchronous script — the one primary distinction is
that doc.write() ensures that these unfavorable behaviours will manifest
themselves, whereas different synchronous scripts could make use of alternate
optimisations to sidestep them.
N.B. This audit and, accordingly, this text, solely offers with
script injection utilizing doc.write() — not its utilization typically. The MDN
entry for
doc.write()
does a very good job of discouraging its use.
What Makes Scripts Sluggish?
There are a selection of issues that may make common, synchronous scripts
gradual:
- Synchronous JS can block DOM development whereas the file is downloading.
- The idea that
synchronous JS blocks DOM development
is simply true
in sure eventualities.
- The idea that
- Synchronous JS at all times blocks DOM development whereas the file is
executing.- It runs in-situ on the actual level it’s outlined, so something outlined after
the script has to attend.
- It runs in-situ on the actual level it’s outlined, so something outlined after
- Synchronous JS by no means blocks downloads of subsequent recordsdata.
- This has been true for virtually 15 years
on the time of writing, but nonetheless stays a typical false impression amongst
builders. That is intently associated to the primary level.
- This has been true for virtually 15 years
The worst case situation is a script that falls into each (1) and (2), which is
extra prone to have an effect on scripts outlined earlier in your HTML. doc.write(),
nevertheless, forces scripts into each (1) and (2) no matter once they’re
outlined.
The Preload Scanner
The explanation scripts by no means block subsequent downloads is due to one thing
known as the Preload Scanner. The Preload Scanner is a secondary, inert,
download-only parser that’s liable for working down the HTML and
asynchronously requesting any out there subresources it would discover, mainly
something contained in src or href attributes, together with photos, scripts,
stylesheets, and so forth. Because of this, recordsdata fetched by way of the Preload Scanner are
parallelised, and might be downloaded asynchronously alongside different (probably
synchronous) sources.
The Preload Scanner is decoupled from the first parser, which is accountable
for establishing the DOM, the CSSOM, working scripts, and so forth. Which means
a big majority of recordsdata we fetch are completed so asynchronously and in
a non-blocking method, together with some synchronous scripts. That is why not all
blocking scripts block throughout their obtain part — they could have been fetched by
the Preload Scanner earlier than they have been truly wanted, thus in a non-blocking
method.
The Preload Scanner and the first parser start processing the HTML at
more-or-less the identical time, so the Preload Scanner doesn’t actually get a lot of
a head begin. That is why early scripts usually tend to block DOM
development throughout their obtain part than late scripts: the first parser
is extra prone to encounter the related <script src> ingredient whereas the file
is downloading if the <script src> ingredient is early within the HTML. Late (e.g.
at-</physique>) synchronous <script src>s usually tend to be fetched by the
Preload Scanner whereas the first parser continues to be hung up doing work earlier in
the web page.
Put merely, scripts outlined earlier within the web page usually tend to block on
their obtain than later ones; later scripts usually tend to have been
fetched preemptively and asynchronously by the Preload Scanner.
doc.write() Hides Recordsdata From the Preload Scanner
As a result of the Preload Scanner offers with tokeniseable src and href attributes,
something buried in JavaScript is invisible to it:
<script>
doc.write('<script src=file.js></script>')
</script>
This isn’t a reference to a script; it is a string in JS. Which means the
browser can’t request this file till it’s truly run the <script> block
that inserts it, which may be very a lot just-in-time (and too late).
doc.write() forces scripts to dam DOM development throughout their
obtain by hiding them from the Preload Scanner.
What About Async Snippets?
Async snippets such because the one under undergo the identical destiny:
<script>
var script = doc.createElement('script');
script.src = 'file.js';
doc.head.appendChild(script);
</script>
Once more, file.js will not be a filepath — it’s a string! It’s not till the browser has
run this script that it places a src attribute into the DOM and might then request
it. The first distinction right here, although, is that scripts injected this fashion are
asynchronous by default. Regardless of being hidden from the Preload Scanner, the
influence is negligible as a result of the file is implicitly asynchronous anyway.
That stated, async snippets are nonetheless an
anti-pattern — don’t use them.
doc.write() Executes Synchronously
doc.write() is sort of solely used to conditionally load
a synchronous script. For those who simply want a blocking script, you’d use a easy
<script src> ingredient:
<script src=file.js></script>
For those who wanted to conditionally load an asynchronous script, you’d add
some if/else logic to your async snippet.
<script>
if (situation) {
var script = doc.createElement('script');
script.src = 'file.js';
doc.head.appendChild(script);
}
</script>
If it’s essential conditionally load a synchronous script, you’re kinda caught…
Scripts injected with, for instance, appendChild are, per the spec,
asynchronous. If it’s essential inject a synchronous file, one of many solely
simple choices is doc.write():
<script>
if (situation) {
doc.write('<script src=file.js></script>')
}
</script>
This ensures a synchronous execution, which is what we would like, nevertheless it additionally
ensures a synchronous fetch, as a result of that is hidden from the Preload Scanner,
which is what we don’t need.
doc.write() forces scripts to dam DOM development throughout their
execution by being synchronous by default.
Is It All Unhealthy?
The placement of the doc.write() in query makes an enormous distinction.
As a result of the Preload Scanner works most successfully when it’s coping with
subresources later within the web page, doc.write() earlier within the HTML is much less
dangerous.
Early doc.write()
<head>
...
<script>
doc.write('<script src=https://slowfil.es/file?kind=js&delay=1000></script>')
</script>
<hyperlink rel=stylesheet href=https://slowfil.es/file?kind=css&delay=1000>
...
</head>
For those who put a doc.write() because the very very first thing in your <head>, it’s
going to behave the very same as an everyday <script src> — the Preload Scanner
wouldn’t have had a lot of a head begin anyway, so we’ve already missed out on
the possibility of an asynchronous fetch:

doc.write() as the very first thing within the <head>. FCP is at 2.778s.Above, we see that the browser has managed to parallelise the requests: the
main parser ran and injected the doc.write(), whereas the Preload
Scanner fetched the CSS.
Owing to CSS’ Highest precedence, it is going to at all times be requested earlier than
Excessive precedence JS, no matter the place every is outlined.
If we change the doc.write() with a easy <script src>, we’d see the
very same behaviour, that means on this particular occasion, doc.write() is
no extra dangerous than an everyday, synchronous script:
<head>
...
<script src=https://slowfil.es/file?kind=js&delay=1000></script>
<hyperlink rel=stylesheet href=https://slowfil.es/file?kind=css&delay=1000>
...
</head>
This yields an equivalent waterfall:

<script src> as an alternative of doc.write(). FCP is at 2.797s.As a result of the Preload Scanner was unlikely to search out both variant, we don’t
discover any actual degradation.
Late doc.write()
<head>
...
<hyperlink rel=stylesheet href=https://slowfil.es/file?kind=css&delay=1000>
<script>
doc.write('<script src=https://slowfil.es/file?kind=js&delay=1000></script>')
</script>
...
</head>
As a result of JS can write/learn to/from the CSSOM, all browsers will halt execution of
any synchronous JS if there may be any previous, pending CSS. In impact, CSS
blocks
JS,
and on this instance, serves to cover the doc.write() from the Preload
Scanner.
Thus, doc.write() later within the web page does turn out to be extra extreme. Hiding
a file from the Preload Scanner — and solely surfacing it to the browser the precise
second we’d like it — goes to make its whole fetch a blocking motion. And,
as a result of the doc.write() file is now being fetched by the first parser
(i.e. the principle thread), the browser can’t full another work whereas the file
is on its manner. Blocking on prime of blocking.
As quickly as we disguise the script file from the Preload Scanner, we discover
drastically completely different behaviour. By merely swapping the doc.write() and
the rel=stylesheet round, we get a a lot, a lot slower expertise:

doc.write() late within the <head>. FCP is at 4.073s.Now that we’ve hidden the script from the Preload Scanner, we lose all
parallelisation and incur a a lot bigger penalty.
It Will get Worse…
The entire motive I’m penning this submit is that I’ve a shopper in the meanwhile who
is utilizing doc.write() late within the <head>. As we now know, this pushes
each the fetch and the execution on the principle thread. As a result of browsers are
single-threaded, because of this not solely are we incurring community delays
(due to a synchronous fetch), we’re additionally leaving the browser unable to work
on the rest for all the length of the script’s obtain!

fetch. This doesn’t occur when recordsdata are fetched from the Preload Scanner.
Keep away from doc.write()
In addition to exhibiting unpredictable and buggy behaviour as keenly harassed in
the MDN and
Google articles,
doc.write() is gradual. It ensures each a blocking fetch and a blocking
execution, which holds up the parser for a lot longer than needed. Whereas it
doesn’t introduce any new or distinctive efficiency points per se, it simply forces
the worst of all worlds.
Keep away from doc.write() (however not less than now you recognize why).
This Net Efficiency submit is tagged with:
Incessantly Requested Questions
Why is doc.write() unhealthy for efficiency?
doc.write() forces scripts to dam DOM development throughout their obtain by hiding them from the Preload Scanner. Which means scripts injected with doc.write() are at all times absolutely synchronous.

