Delay Third-Party Scripts Until the Visitor Interacts
Holds back the scripts you list (chat widgets, heatmaps, social widgets) until the visitor first scrolls, taps, clicks or presses a key, or after a timeout, so they no longer slow down the initial page load.
Opens WPIDE on
Code
// Script handles, or fragments of their URL, to delay.
$wpide_delay_scripts = array( 'hotjar', 'tawk', 'intercom', 'crisp', 'facebook', 'connect.facebook.net', 'static.hotjar.com' );
// Seconds after which delayed scripts load anyway (0 = only on interaction).
$wpide_delay_timeout = 8;
add_filter( 'script_loader_tag', function ( $tag, $handle, $src ) use ( $wpide_delay_scripts ) {
$match = false;
foreach ( $wpide_delay_scripts as $needle ) {
if ( $handle === $needle || ( $src && false !== strpos( $src, $needle ) ) ) {
$match = true;
break;
}
}
if ( ! $match || ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $tag;
}
$tags = new WP_HTML_Tag_Processor( $tag );
while ( $tags->next_tag( 'script' ) ) {
$tags->set_attribute( 'type', 'text/wpide-delay' );
}
return $tags->get_updated_html();
}, 30, 3 );
add_action( 'wp_footer', function () use ( $wpide_delay_timeout ) {
?>
<script>
(function () {
var done = false, events = ['scroll', 'pointerdown', 'keydown', 'touchstart', 'mousemove'];
function run() {
if (done) { return; }
done = true;
events.forEach(function (e) { window.removeEventListener(e, run, { passive: true }); });
var list = Array.prototype.slice.call(document.querySelectorAll('script[type="text/wpide-delay"]'));
(function next() {
var old = list.shift();
if (!old) { return; }
var s = document.createElement('script');
Array.prototype.forEach.call(old.attributes, function (a) { if (a.name !== 'type') { s.setAttribute(a.name, a.value); } });
if (old.src) { s.onload = s.onerror = next; s.async = false; } else { s.text = old.text; }
old.parentNode.replaceChild(s, old);
if (!old.src) { next(); }
})();
}
events.forEach(function (e) { window.addEventListener(e, run, { passive: true }); });
<?php if ( $wpide_delay_timeout > 0 ) : ?>
setTimeout(run, <?php echo (int) $wpide_delay_timeout * 1000; ?>);
<?php endif; ?>
})();
</script>
<?php
}, 999 );
Notes
List handles or parts of script URLs; never delay scripts that render content above the fold or that other scripts depend on.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.