UX Collective

We believe designers are thinkers as much as they are makers. https://linktr.ee/uxc

Follow publication

Boost page speed with “mindful loading” of third party scripts

George Adamson
UX Collective
Published in
8 min readSep 9, 2020

--

“Can you just add this little script to the page?”

Screenshot from a Lighthouse report indicating slow page speed

you try the usual quick wins that you googled last time…

…but that’s not enough,

Let’s rethink. When do we actually *need* that script?

(a) We need it immediately on page load

(b) We need it later

Postponing the script in the Browser

Solution 1: Late load

Solution 2: Lazy load

Solution 3: Load on demand

Use the server too

Example of a star-ratings widget

Option 1: Bespoke markup & styles

Option 2: Run the widget script server-side

Other [equally vital] considerations:

Avoid loading the script repeatedly

Testing whether the script is already on the page

if (document.querySelector('script[src="https://path/to/the.js"'))
// This helper returns a Promise that will resolve when the script is loaded and ready:async function awaitScriptLoad(isScriptReady) {  return new Promise((resolve, reject) => {    const intervalId = setInterval(() => {      if (isScriptReady()) {        // Tidy up & tell the caller it's safe to run the script:        clearInterval(intervalId);        clearTimeout(timeoutId);        resolve();      }    }, 250);    // Recommended: Define a timeout too:    const timeoutId = setTimeout(() => {      clearInterval(intervalId);      reject();    }, 30000);  });}
// This will be your own helper to detect whether script is ready:
// This example tests for the object created by Video.js but some third parties load more scripts that add methods. You may need to detect them too.
function isScriptLoadedAndReady() { return 'videojs' in window;}
// Wait for the Promise to resolve:
// Sometimes you may also need to catch a failure and handle it.
await awaitScriptLoad(isScriptLoadedAndReady);
// Now do something with the script.

Accessibility

No-JS

The UX Collective donates US$1 for each article published in our platform. This story contributed to Bay Area Black Designers: a professional development community for Black people who are digital designers and researchers in the San Francisco Bay Area. By joining together in community, members share inspiration, connection, peer mentorship, professional development, resources, feedback, support, and resilience. Silence against systemic racism is not an option. Build the design community you believe in.

--

--

Written by George Adamson

Mobile & web dev lead, interaction design & UX. Over enthusiastic comic conference speaker & mentor on web tech. (suoıl ǝɥʇ ɥʇıʍ ǝʞolq ǝɥʇ ʇou ɯ,ı 'ou puɐ)

Responses (1)