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.
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.
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 readchat script requestedThe 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.