Today I Learned - Rocky Kev

TIL using defer/async

POSTED ON:

TAGS:

So an old and often-touted best practice for performance has been to load your JavaScript in the footer of the document to avoid render blocking of scripts. By putting it in the footer, the DOM is constructed before your scripts have a chance to run.

With the advent of JS applications being the full site, however, it has been more commonplace in certain architectures to place <script> elements in the document <head>.

Instead, you're better off just using JS resource hints like async or defer.

async and defer both load JavaScript asynchronously without render blocking, but async executes as soon as possible while defer runs in sequence toward the end of the loading process, just before the DOMContentLoaded event.

For async:
Once the resource is gathered from the internet, it fires. That's useful for libraries/frameworks that your code is piggybacking off of. Or JS that needs to load, like configuration files.

What about defer:
It's useful for when you need to finally start your Javascript.

Now that the JS framework started, activate your code.

And what is DOMContentLoaded? It's when HTML is ready.

The DOMContentLoaded event fires when the HTML document has been completely parsed, and all deferred scripts (<script defer src="…"> and <script type="module">) have downloaded and executed. It doesn't wait for other things like images, subframes, and async scripts to finish loading.

via MDN - Window: DOMContentLoaded event

via What's The Difference Between Async & Defer?


Related TILs

Tagged:

TIL Performance tests

While doing performance tests, I was curious how long a loop was running. I used the performance.now() trick.

TIL self-hosting your own Google Fonts

I'm all for self-hosting. So seeing this question asked 'Should you self-host Google Fonts?', my immediate answer is ABSOLUTELY. But here's the edge-cases.

TIL loading third-party scripts onto service workers

An alternative to self-hosting scripts would be using Service Workers to cache them. This can give you greater control over how often they are re-fetched from the network. This could also be used to create a loading strategy where requests for non-essential third parties are throttled until the page reaches a key user moment.