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.
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:
Async Script
Dynamic Loading
Deferred Loading
<!-- Recommended: Async loading -->
< script async src = "https://cdn.taginsight.com/listener_client_204_project_664.js" ></ script >
// 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 );
});
// 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 );
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'
}
}
}
};
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
});
}
}
};
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 : {
'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 }
}
✅ Loading
✅ Data Collection
✅ Memory
✅ Network
✅ Monitoring
Check script loading method
Verify CDN response time
Review sampling configuration
Consider deferred loading
Check event buffer size
Review SPA configuration
Enable aggressive cleanup
Limit stored events
Increase batch size
Extend batch timeout
Implement sampling
Use beacon API
Next steps