Skip to main content

Overview

Performance is critical for modern websites. This guide helps you optimize your Tag Insight implementation to ensure minimal impact on page load times and user experience while maintaining comprehensive tracking coverage.
Tag Insight is designed to be lightweight, but proper implementation and configuration can further reduce any performance impact.

Performance Impact Analysis

Understanding the Load

Tag Insight’s typical performance profile:

Script Size

~50-200KB (gzipped: ~15-60KB)

Load Time

<100ms on fast connections

Memory Usage

~2-5MB in browser memory

CPU Impact

<1% during normal operation

Measuring Impact

// Measure Tag Insight loading performance
performance.mark('taginsight-start');

// Load Tag Insight
var script = document.createElement('script');
script.src = 'https://cdn.taginsight.com/listener_client_204_project_664.js';
script.onload = function() {
  performance.mark('taginsight-end');
  performance.measure('taginsight-load', 'taginsight-start', 'taginsight-end');
  
  const measure = performance.getEntriesByName('taginsight-load')[0];
  console.log('Tag Insight loaded in:', measure.duration, 'ms');
};
document.head.appendChild(script);

Loading Strategies

Asynchronous Loading

Always load Tag Insight asynchronously:
<!-- Recommended: Async loading -->
<script async src="https://cdn.taginsight.com/listener_client_204_project_664.js"></script>

Priority Loading

Control when Tag Insight loads:
// High-priority pages (e.g., checkout)
if (isCheckoutPage()) {
  // Load immediately for critical tracking
  loadTagInsightImmediately();
} else if (isProductPage()) {
  // Load after LCP for better performance
  new PerformanceObserver((list) => {
    const entries = list.getEntries();
    const lastEntry = entries[entries.length - 1];
    if (lastEntry.element) {
      loadTagInsight();
    }
  }).observe({ type: 'largest-contentful-paint', buffered: true });
} else {
  // Low-priority pages: defer loading
  if ('requestIdleCallback' in window) {
    requestIdleCallback(loadTagInsight);
  } else {
    setTimeout(loadTagInsight, 2000);
  }
}

Data Collection Optimization

Smart Sampling

Reduce data volume intelligently:
window._tagInsightConfig = {
  sampling: {
    enabled: true,
    
    // Default sampling rate
    default: 0.1, // 10% of all events
    
    // Event-specific rates
    events: {
      // Critical events: always track
      'purchase': 1.0,
      'checkout_error': 1.0,
      'payment_failed': 1.0,
      
      // High-value events: higher sampling
      'add_to_cart': 0.5,
      'search': 0.3,
      
      // Low-value events: lower sampling
      'page_view': 0.1,
      'scroll_depth': 0.05,
      'mouse_move': 0.01
    },
    
    // User-based sampling
    userSampling: {
      enabled: true,
      method: 'session', // 'session' or 'user'
      rate: 0.2, // Sample 20% of sessions
      
      // Always include certain users
      includeRules: [
        { property: 'user_type', value: 'vip' },
        { property: 'test_group', value: 'always_track' }
      ]
    }
  }
};

Event Batching

Reduce network requests:
window._tagInsightConfig = {
  batching: {
    enabled: true,
    
    // Batch configuration
    maxBatchSize: 50,        // Max events per batch
    batchTimeout: 5000,      // Send batch after 5 seconds
    maxQueueSize: 500,       // Max events to queue
    
    // Adaptive batching
    adaptive: {
      enabled: true,
      // Adjust based on connection speed
      slowConnection: {
        maxBatchSize: 100,
        batchTimeout: 10000
      },
      fastConnection: {
        maxBatchSize: 25,
        batchTimeout: 2000
      }
    },
    
    // Priority flushing
    priorityEvents: [
      'purchase',
      'checkout_error',
      'signup_complete'
    ]
  }
};

Selective Tracking

Track only what matters:
window._tagInsightConfig = {
  // Exclude non-essential tracking
  exclude: {
    // Page patterns to skip
    pages: [
      '/admin/*',
      '/test/*',
      '*/preview'
    ],
    
    // Events to ignore
    events: [
      'heartbeat',
      'ping',
      'debug_*'
    ],
    
    // Skip tracking for bots
    userAgents: [
      'bot', 'crawler', 'spider',
      'Googlebot', 'bingbot', 'Slackbot'
    ]
  },
  
  // Include only specific events
  include: {
    onlyTheseEvents: [
      'page_view',
      'conversion',
      'error'
    ]
  }
};

Memory Management

Limit Event Buffer

Prevent memory buildup:
window._tagInsightConfig = {
  memory: {
    // Limit stored events
    maxStoredEvents: 1000,
    
    // Clear old events
    eventTTL: 300000, // 5 minutes
    
    // Aggressive cleanup for SPAs
    spa: {
      enabled: true,
      clearOnRouteChange: true,
      maxEventsPerRoute: 100
    },
    
    // Memory pressure handling
    pressureHandling: {
      enabled: true,
      threshold: 0.9, // 90% memory usage
      action: 'flush' // 'flush' or 'drop'
    }
  }
};

Data Structure Optimization

Minimize memory footprint:
// Optimize event payloads
window._tagInsightConfig = {
  optimization: {
    // Remove redundant data
    deduplication: {
      enabled: true,
      fields: ['page_url', 'referrer', 'user_agent']
    },
    
    // Compress large values
    compression: {
      enabled: true,
      threshold: 1024, // Compress values > 1KB
      fields: ['custom_data', 'product_list']
    },
    
    // Truncate long strings
    truncation: {
      enabled: true,
      maxLength: 500,
      fields: ['description', 'error_stack']
    }
  }
};

Network Optimization

CDN Configuration

Optimize delivery:
// Use nearest CDN edge
window._tagInsightConfig = {
  cdn: {
    // Auto-select best endpoint
    autoSelect: true,
    
    // Regional endpoints
    endpoints: {
      'us': 'https://us.cdn.taginsight.com',
      'eu': 'https://eu.cdn.taginsight.com',
      'asia': 'https://asia.cdn.taginsight.com'
    },
    
    // Fallback options
    fallback: {
      enabled: true,
      endpoints: [
        'https://cdn.taginsight.com',
        'https://backup.taginsight.com'
      ]
    }
  }
};

Request Optimization

Minimize network impact:
// Optimize network requests
window._tagInsightConfig = {
  network: {
    // Use beacon API for reliability
    useBeacon: true,
    
    // Retry configuration
    retry: {
      enabled: true,
      maxAttempts: 3,
      backoff: 'exponential',
      
      // Don't retry on slow connections
      skipOnSlowConnection: true
    },
    
    // Connection-aware behavior
    connectionAware: {
      enabled: true,
      
      // Reduce tracking on slow connections
      '2g': { samplingRate: 0.01 },
      '3g': { samplingRate: 0.1 },
      '4g': { samplingRate: 1.0 },
      'wifi': { samplingRate: 1.0 }
    }
  }
};

Browser Optimization

Web Workers

Offload processing:
// Use Web Worker for heavy processing
window._tagInsightConfig = {
  webWorker: {
    enabled: true,
    
    // Worker configuration
    workerUrl: '/taginsight-worker.js',
    
    // Offload these operations
    offload: [
      'validation',
      'transformation',
      'compression'
    ],
    
    // Fallback for unsupported browsers
    fallbackToMainThread: true
  }
};

// taginsight-worker.js
self.addEventListener('message', function(e) {
  const { type, data } = e.data;
  
  switch(type) {
    case 'validate':
      const validated = validateEvent(data);
      self.postMessage({ type: 'validated', data: validated });
      break;
    // Handle other operations
  }
});

Lazy Loading Components

Load features on demand:
// Lazy load advanced features
window._tagInsightConfig = {
  lazyLoad: {
    enabled: true,
    
    // Features to lazy load
    features: {
      'heatmaps': {
        trigger: 'manual',
        url: '/taginsight-heatmaps.js'
      },
      'session_replay': {
        trigger: 'user_action',
        url: '/taginsight-replay.js'
      },
      'advanced_analytics': {
        trigger: 'page_type',
        condition: 'checkout',
        url: '/taginsight-advanced.js'
      }
    }
  }
};

Performance Monitoring

Real User Monitoring

Track actual impact:
// Monitor Tag Insight performance
window._tagInsightConfig = {
  rum: {
    enabled: true,
    
    // Metrics to track
    metrics: [
      'script_load_time',
      'initialization_time',
      'event_processing_time',
      'network_request_time'
    ],
    
    // Performance budgets
    budgets: {
      script_load_time: 200, // ms
      event_processing_time: 10, // ms
      memory_usage: 5 // MB
    },
    
    // Alert on violations
    onBudgetExceeded: function(metric, value, budget) {
      console.warn(`Performance budget exceeded: ${metric}`, {
        actual: value,
        budget: budget
      });
    }
  }
};

Performance API Integration

Use browser Performance API:
// Track key metrics
class TagInsightPerformance {
  static measure() {
    const navigation = performance.getEntriesByType('navigation')[0];
    const tagInsightResource = performance.getEntriesByName(
      'https://cdn.taginsight.com/listener_client_204_project_664.js'
    )[0];
    
    return {
      // Page metrics
      pageLoadTime: navigation.loadEventEnd - navigation.fetchStart,
      domReady: navigation.domContentLoadedEventEnd - navigation.fetchStart,
      
      // Tag Insight metrics
      scriptLoadTime: tagInsightResource ? tagInsightResource.duration : 0,
      scriptSize: tagInsightResource ? tagInsightResource.transferSize : 0,
      
      // Impact calculation
      impactPercentage: tagInsightResource ? 
        (tagInsightResource.duration / navigation.loadEventEnd) * 100 : 0
    };
  }
}

Best practices by Site Type

High-Traffic Sites

{
  sampling: { default: 0.1 },
  batching: { maxBatchSize: 100 },
  cdn: { cache: 'aggressive' },
  exclude: { events: ['scroll', 'time_on_page'] }
}
{
  sampling: { 
    'product_view': 0.5,
    'add_to_cart': 1.0,
    'purchase': 1.0
  },
  priority: ['checkout', 'cart'],
  lazyLoad: { enabled: true }
}
{
  spa: { enabled: true },
  memory: { aggressive: true },
  webWorker: { enabled: true },
  batching: { adaptive: true }
}

Performance Checklist

Loading
  • Async/defer script loading
  • Load after critical resources
  • Use resource hints (preconnect)
Data Collection
  • Implement sampling
  • Enable batching
  • Exclude unnecessary events
Memory
  • Limit event buffer
  • Clear old data
  • Optimize payloads
Network
  • Use nearest CDN
  • Enable compression
  • Implement retry logic
Monitoring
  • Track performance metrics
  • Set performance budgets
  • Monitor real user impact

Troubleshooting Performance

  1. Check script loading method
  2. Verify CDN response time
  3. Review sampling configuration
  4. Consider deferred loading
  1. Check event buffer size
  2. Review SPA configuration
  3. Enable aggressive cleanup
  4. Limit stored events
  1. Increase batch size
  2. Extend batch timeout
  3. Implement sampling
  4. Use beacon API

Next steps