Delay JavaScript execution in GTM

Delaying JavaScript execution is a powerful optimization technique that improves webpage performance by postponing the loading and execution of JavaScript files until a user interaction occurs, such as mouse movement, touch, scroll, or key press.

This approach helps reduce the initial loading time of web pages, which can significantly improve performance metrics important for user experience and SEO, such as First Contentful Paint (FCP), Largest Contentful Paint (LCP), and Time to Interactive (TTI). These improvements are critical because Google uses them as part of its Core Web Vitals, which influence search engine rankings.

One practical implementation of this technique is found in the WP Rocket plugin for WordPress, which includes a feature to delay JavaScript execution. This feature is designed to boost site performance by only loading JavaScript files and inline scripts after the user starts interacting with the page.

Using this feature allows you deley the loading og the GTM container but it means the all tags in container are delayed and this may not always be optimal. While delaying JavaScript execution can improve page speed and user experience, it may not be suitable for all scripts, especially those critical for tracking or analytics, as it could lead to incomplete or inaccurate data collection. Therefore, it’s recommended to carefully choose which scripts to delay, balancing performance improvements with the functionality and data collection needs of your site.

GTM Kit can be configured to push the event load_delayed_js on page and the script that does this can be delayed by af pagespeed optimization plugin. This means that load_delayed_js will be pushed to the GTM container on user activity. You can use this in GTM to define a trigger that fires on user activity.