Today I Learned - Rocky Kev

TIL why google recommends you avoid document.write()

POSTED ON:

TAGS:

If you’ve ever run a Lighthouse test before, there’s a high chance you’ve seen the audit Avoid document.write():

via Why Not document.write()?

document.write() Hides Files From the Preload Scanner

The Preload Scanner is a secondary, inert, download-only parser that’s responsible for running down the HTML and asynchronously requesting any available subresources it might find, chiefly anything contained in src or href attributes, including images, scripts, stylesheets, etc. As a result, files fetched via the Preload Scanner are parallelised, and can be downloaded asynchronously alongside other (potentially synchronous) resources.

<script>
document.write('<script src=file.js><\/script>')
</script>

This means that the browser can’t request this file until it’s actually run the <script> block that inserts it, which is very much just-in-time (and too late).


Related TILs

Tagged:

TIL why google recommends you avoid document.write()

By injecting it with code, it bypasses the preload scanner. This means that the browser can’t request this file until it’s actually run the '<script>' block that inserts it, which is very much just-in-time (and too late).

TIL prioritizing Javascript

... async and defer attributes should be used where possible to avoid render blocking of the DOM. Render blocking is when the browser must halt all rendering of the page in order to process a resource that the page depends on.

TIL problem with AJAX

Synchronous XHR is harmful for performance because the event loop and main thread is blocked until the request is finished, resulting in the page hanging until the data becomes available. fetch is a much more effective and efficient alternative with a simpler API, and has no support for synchronous fetching of data.