滚动触发脚本重复插入问题求解决:GDPR相关Google脚本优化
解决Google GDPR脚本重复插入及性能优化问题
核心修改方案
要解决重复插入脚本的问题,核心是添加加载状态标记,同时优化滚动事件的性能消耗,避免影响Lighthouse/PageSpeed评分。以下是两种可行的实现方式:
方式一:基于滚动事件的优化版代码
<script> // 标记脚本是否已加载 let gdprScriptLoaded = false; const scrollFromTop = $("#cargars").offset().top; // 防抖函数:减少滚动事件触发频率,优化性能 function debounce(func, delay = 100) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => func.apply(this, args), delay); }; } // 滚动触发的GDPR脚本加载逻辑 function loadGDPRScriptOnScroll() { if (!gdprScriptLoaded && ($(this).scrollTop() + $(window).height() > scrollFromTop)) { gdprScriptLoaded = true; // 标记为已加载,避免重复执行 const script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://fundingchoicesmessages.google.com/i/pub-9225993600367994'; // 脚本加载完成后解绑滚动事件,彻底终止监听 script.onload = () => $(document).off('scroll'); document.getElementById('cargars').appendChild(script); } } // 绑定防抖后的滚动事件 $(document).scroll(debounce(loadGDPRScriptOnScroll)); </script>
方式二:使用Intersection Observer API(更优性能)
推荐用浏览器原生的Intersection Observer替代滚动事件监听,它不会频繁触发回调,对页面性能影响更小,更符合现代前端性能优化标准:
<script> let gdprScriptLoaded = false; const targetElement = document.getElementById('cargars'); // 创建观察器:当目标元素进入视口时触发 const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting && !gdprScriptLoaded) { gdprScriptLoaded = true; const script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://fundingchoicesmessages.google.com/i/pub-9225993600367994'; targetElement.appendChild(script); observer.disconnect(); // 完成加载后停止观察,释放资源 } }); }, { threshold: 0.1 }); // 元素进入视口10%时触发逻辑 observer.observe(targetElement); </script>
关键改动说明
- 加载状态标记:通过
gdprScriptLoaded变量记录脚本是否已插入,从根源上避免重复加载。 - 防抖处理:针对滚动事件添加防抖,减少不必要的回调触发,降低浏览器性能消耗。
- 事件解绑/观察者销毁:脚本加载完成后立即终止监听,避免后续无效的资源占用。
- Intersection Observer优势:原生API无需依赖jQuery,触发逻辑更精准,不会像滚动事件那样在用户滚动时持续触发,对Lighthouse评分更友好。
内容的提问来源于stack exchange,提问作者JA MA OmegaYalfa
相关产品推荐
相关产品推荐

