Skip to content
jshacks.dev
Performance

Load third-party scripts after interaction

Inject a chat widget or analytics script only after the first scroll, click or key press, so it does not compete with your own code during page load.

1 min read
Summarize in AI

A chat widget can pull in hundreds of kilobytes that nobody needs until they actually look for help. Waiting for the first interaction keeps it out of the critical load.

widgets.jsJavaScript
let loaded = false;

function loadChat() {
  if (loaded) return;
  loaded = true;
  const script = document.createElement('script');
  script.src = 'https://widget.example.test/chat.js';
  script.async = true;
  document.head.append(script);
  console.log('chat script requested');
}

for (const type of ['pointerdown', 'keydown', 'scroll']) {
  addEventListener(type, loadChat, { once: true, passive: true });
}

setTimeout(loadChat, 8000); // fallback for visitors who only read
Text
chat script requested

The loaded flag makes sure only one of the listeners and the timer injects the script. The once option removes a listener after its first call and passive tells the browser it will not call preventDefault.

The widget is slower on its first use, because it loads on demand. Do not delay scripts that a feature needs immediately, such as a consent manager that must run before analytics. Facade patterns, where a static button stands in until the click, give an even earlier first paint. See Chrome's third-party loading guide.

Also inBrowser
Share

More snippets

Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.