You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:Cookie已设置时嵌入Google Analytics方案(规避document.write)

Hey there! Smart move steering clear of document.write — it can mess with page rendering, especially if executed after the page has loaded, and it’s definitely not ideal for modern web dev. Here’s a clean, reliable way to implement your requirement:

First, let’s create a helper to verify the cookie exists (this avoids partial matches that a simple indexOf might catch):

function hasTargetCookie() {
  // Replace 'cookie' with your actual cookie name
  const targetCookie = 'cookie';
  return document.cookie.split(';').some(cookie => {
    const trimmed = cookie.trim();
    return trimmed.startsWith(`${targetCookie}=`);
  });
}

Step 2: Dynamically Load the GA Script

Instead of document.write, we’ll build the script element programmatically and add it to the DOM — this is non-blocking and safe even after the page loads:

function loadGoogleAnalytics() {
  // Create the script tag
  const gaScript = document.createElement('script');
  gaScript.async = true;
  gaScript.src = 'https://www.googletagmanager.com/gtag/js?id=YOUR_GA_ID'; // Swap with your tracking ID

  // Append to the document head
  document.head.appendChild(gaScript);

  // Initialize GA once the script finishes loading
  gaScript.onload = function() {
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'YOUR_GA_ID'); // Swap with your tracking ID
  };
}

Step 3: Put It All Together

Run the check and load GA only if the cookie is present — you can place this at the end of your <body> or wrap it in a DOM-ready listener:

// Execute once the page is ready
if (hasTargetCookie()) {
  loadGoogleAnalytics();
}

Why This Is Better Than document.write

  • Non-blocking: The GA script loads asynchronously, so it won’t slow down your page’s initial render.
  • DOM-safe: Works even if you run the code after the page has finished loading (unlike document.write, which can overwrite the entire page in that scenario).
  • Maintainable: Separated into reusable functions, so it’s easy to tweak the cookie check or GA setup later.

内容的提问来源于stack exchange,提问作者ask

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:35:59