Lazy load cho Google tag manager tăng tốc trên PageSpeed

Bạn tích hợp nhúng code Google tag manager vào check trên google speed insights thử xem, tất nhiên là tệ hơn chưa kể đã nhúng các thẻ vào google tag manager này. Vậy đây là cách làm nó tải chậm mà điểm lại được cải thiện.

How to integrated code Google tag manager lazy load for Google tag manager.

Đặt code dưới vào thẻ <head> thay id GTM của bạn thế là xong:

<script>
document.addEventListener('DOMContentLoaded', () => {
	/** init gtm after 3500 seconds - this could be adjusted */
	setTimeout(initGTM, 3500);
});
document.addEventListener('scroll', initGTMOnEvent);
document.addEventListener('mousemove', initGTMOnEvent);
document.addEventListener('touchstart', initGTMOnEvent);

function initGTMOnEvent (event) {
	initGTM();
	event.currentTarget.removeEventListener(event.type, initGTMOnEvent); // remove the event listener that got triggered
}

function initGTM () {
	if (window.gtmDidInit) return false;
	window.gtmDidInit = true; // flag to ensure script does not get added to DOM more than once.
	const script = document.createElement('script');
	script.type = 'text/javascript';
	script.async = true;
	script.onload = () => { dataLayer.push({ event: 'gtm.js', 'gtm.start': (new Date()).getTime(), 'gtm.uniqueEventId': 0 }); } // this part ensures PageViews is always tracked
	script.src = 'https://www.googletagmanager.com/gtm.js?id=YOUR_ID_GTM';
	document.head.appendChild(script);
}
</script>

 

Tin tức khác