Reader small image

You're reading from  JavaScript Design Patterns

Product typeBook
Published inMar 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781804612279
Edition1st Edition
Languages
Right arrow
Author (1)
Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

Right arrow

Asset Loading Strategies and Executing Code off the Main Thread

There are situations in the life cycle of an application where loading more JavaScript is inevitable. This chapter details techniques to mitigate the impact of such situations. You’ll learn about asset loading optimizations such as a script element’s async, the defer attribute, the impact of type="module", and the link element’s rel (relationship) attribute’s preconnect, preload, and prefetch values. Next, you will further optimize script loading using Next.js’ Script component and its different options. The chapter wraps up with an exploration of reasons to execute JavaScript code off the main thread and an approach to do so.

In this chapter, we’ll cover the following topics:

  • How to control asset loading more granularly with a script’s async and defer attributes, and links with preconnect, preload, and prefetch
  • Further optimization opportunities...

Technical requirements

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/Javascript-Design-Patterns

Asset loading optimization – async, defer, preconnect, preload, and prefetch

When using script to load and execute JavaScript, there are HTML attributes of script we can use to control the loading and execution.

We can rely on the difference between external scripts and inline scripts; we can also use the async, defer, and type="module" attributes.

We’ll start by defining external and inline scripts, then the async and defer attributes. Finally, we’ll look at classic and module scripts via the type="module" attribute.

External scripts use the src attribute to point to a separate JavaScript file; for example, what follows is an external script that will load and evaluate ./script.js when it’s encountered:

<script src="./script.js"></script>

Contrast this with inline scripts, where there is no src attribute; instead, the JavaScript code is in the script tag contents:

<script>
  console...

Using Next.js Script’s strategy option to optimize asset loading

The Next.js Script component gives us more control over script loading behavior, allowing us to improve page load performance.

The strategy prop allows us to control the loading strategy; it defaults to afterInteractive, which will begin loading after some of the Next.js code has run. It can be set to beforeInteractive, in which case the script is loaded and executed before all Next.js code. lazyOnLoad can be used for lower-priority scripts to delay loading until there’s browser idle time.

The final option is experimental; it’s the worker strategy, which will load and run the script in a web worker.

Per the Next.js docs for the Script#strategy option, the following list contains the loading strategies of the script (see the docs: https://nextjs.org/docs/pages/api-reference/components/script#strategy).

There are four different strategies that can be used:

  • beforeInteractive: Load...

Loading and running scripts in a worker thread

One of the Next.js Script strategy options is worker, which loads and runs the script in a web worker. In current Next.js versions, this is achieved via a library called Partytown (https://partytown.builder.io/). The following is from the Partytown documentation:

“Partytown is a lazy-loaded library to help relocate resource-intensive scripts into a web worker, and off of the main thread. Its goal is to help speed up sites by dedicating the main thread to your code, and offloading third-party scripts to a web worker.” Partytown home page – https://partytown.builder.io/

To expand on that definition, JavaScript runs in a single-threaded environment in the browser. “Single-threaded” means we only have one entity able to execute compute operations; non-asynchronous work cannot be done in parallel. The main thread in this context is the browser’s JavaScript execution thread. When loading and executing...

Summary

In this chapter, we’ve covered techniques to control asset and JavaScript loading more granularly.

In order to control script loading using browser built-in functionality, we can use async and defer attributes; we covered their effect on module scripts versus classic scripts. We also looked at using the rel attribute on a link element for resource hints, and what impact preconnect, preload, modulepreload, and prefetch have on resource loading.

We can leverage the Next.js Script component’s strategy prop to control script loading and execution beyond async and defer in the context of a Next.js application.

Finally, we looked at the possibility of running certain scripts off the main JavaScript thread using the Next.js Script worker strategy, powered by the Partytown library.

In this final chapter, we covered asset loading strategies and optimizations such as executing code off the main thread.

This brings us to the end of this book. Hopefully, you...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
JavaScript Design Patterns
Published in: Mar 2024Publisher: PacktISBN-13: 9781804612279
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco