> ## Documentation Index
> Fetch the complete documentation index at: https://docs.taginsight.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Performance optimization

> Optimize Tag Insight implementation for minimal performance impact

## 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.

<Note>
  Tag Insight is designed to be lightweight, but proper implementation and configuration can further reduce any performance impact.
</Note>

## Performance Impact Analysis

### Understanding the Load

Tag Insight's typical performance profile:

<CardGroup cols={2}>
  <Card title="Script Size" icon="file">
    \~50-200KB (gzipped: \~15-60KB)
  </Card>

  <Card title="Load Time" icon="clock">
    \<100ms on fast connections
  </Card>

  <Card title="Memory Usage" icon="memory">
    \~2-5MB in browser memory
  </Card>

  <Card title="CPU Impact" icon="microchip">
    \<1% during normal operation
  </Card>
</CardGroup>

### Measuring Impact

```javascript
// 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:

<Tabs>
  <Tab title="Async Script">
    ```html
    <!-- Recommended: Async loading -->
    <script async src="https://cdn.taginsight.com/listener_client_204_project_664.js"></script>
    ```
  </Tab>

  <Tab title="Dynamic Loading">
    ```javascript
    // Load after critical resources
    window.addEventListener('load', function() {
      var script = document.createElement('script');
      script.src = 'https://cdn.taginsight.com/listener_client_204_project_664.js';
      script.async = true;
      document.head.appendChild(script);
    });
    ```
  </Tab>

  <Tab title="Deferred Loading">
    ```javascript
    // Defer until user interaction
    let tagInsightLoaded = false;

    function loadTagInsight() {
      if (tagInsightLoaded) return;
      tagInsightLoaded = true;
      
      var script = document.createElement('script');
      script.src = 'https://cdn.taginsight.com/listener_client_204_project_664.js';
      document.head.appendChild(script);
    }

    // Load on first interaction
    ['scroll', 'click', 'touchstart'].forEach(event => {
      window.addEventListener(event, loadTagInsight, { once: true });
    });

    // Or after delay
    setTimeout(loadTagInsight, 3000);
    ```
  </Tab>
</Tabs>

### Priority Loading

Control when Tag Insight loads:

```javascript
// 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:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
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:

```javascript
// 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:

```javascript
// 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:

```javascript
// 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:

```javascript
// 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:

```javascript
// 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:

```javascript
// 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:

```javascript
// 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

<AccordionGroup>
  <Accordion title="News/Media Sites">
    ```javascript
    {
      sampling: { default: 0.1 },
      batching: { maxBatchSize: 100 },
      cdn: { cache: 'aggressive' },
      exclude: { events: ['scroll', 'time_on_page'] }
    }
    ```
  </Accordion>

  <Accordion title="E-commerce">
    ```javascript
    {
      sampling: { 
        'product_view': 0.5,
        'add_to_cart': 1.0,
        'purchase': 1.0
      },
      priority: ['checkout', 'cart'],
      lazyLoad: { enabled: true }
    }
    ```
  </Accordion>

  <Accordion title="SaaS Applications">
    ```javascript
    {
      spa: { enabled: true },
      memory: { aggressive: true },
      webWorker: { enabled: true },
      batching: { adaptive: true }
    }
    ```
  </Accordion>
</AccordionGroup>

### 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

<AccordionGroup>
  <Accordion title="Slow Page Load">
    1. Check script loading method
    2. Verify CDN response time
    3. Review sampling configuration
    4. Consider deferred loading
  </Accordion>

  <Accordion title="High Memory Usage">
    1. Check event buffer size
    2. Review SPA configuration
    3. Enable aggressive cleanup
    4. Limit stored events
  </Accordion>

  <Accordion title="Network Congestion">
    1. Increase batch size
    2. Extend batch timeout
    3. Implement sampling
    4. Use beacon API
  </Accordion>
</AccordionGroup>

## Next steps

<CardGroup cols={2}>
  <Card title="Collaboration" icon="users" href="/best-practices/collaboration">
    Share performance tips
  </Card>

  <Card title="Monitoring Setup" icon="chart-line" href="/monitoring/setting-up-audits">
    Configure performance monitoring
  </Card>

  <Card title="Debugging Guide" icon="bug" href="/troubleshooting/debugging">
    Debug performance issues
  </Card>

  <Card title="Multi-Environment" icon="server" href="/implementation/environments">
    Optimize per environment
  </Card>
</CardGroup>
