Introduction
Geographic-based script loading allows you to personalize your website experience based on user location. This can include loading region-specific functionality, compliance scripts for certain countries, or localized features. JavaScript Activator makes it easy to implement geographic-based conditional script loading. This guide will show you how.
Understanding Geographic Script Loading
Geographic script loading enables:
- Region-specific functionality (e.g., different payment methods by country)
- Compliance scripts (e.g., GDPR for EU, CCPA for California)
- Localized features (e.g., currency converters, language selectors)
- Performance optimization (e.g., loading CDN scripts from nearest region)
- Legal requirements (e.g., cookie consent based on jurisdiction)
Detecting User Location
Method 1: IP-Based Geolocation
Use a geolocation service to detect user country:
async function getUserCountry() {
try {
// Using a free geolocation API
const response = await fetch('https://ipapi.co/json/');
const data = await response.json();
return data.country_code; // Returns ISO country code (e.g., 'US', 'GB', 'DE')
} catch (error) {
console.error('Geolocation error:', error);
return 'US'; // Default fallback
}
}
// Use the country code
const userCountry = await getUserCountry();
console.log('User country:', userCountry);
Method 2: Browser Timezone Detection
Use timezone as a proxy for location (less accurate but faster):
function getCountryFromTimezone() {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
// Map timezones to countries (simplified example)
const timezoneMap = {
'America/New_York': 'US',
'America/Los_Angeles': 'US',
'Europe/London': 'GB',
'Europe/Paris': 'FR',
'Europe/Berlin': 'DE',
'Asia/Tokyo': 'JP',
// Add more mappings as needed
};
return timezoneMap[timezone] || 'US';
}
Method 3: Server-Side Detection
For more reliable detection, use server-side geolocation:
// Server sets data attribute
<body data-user-country="US">
// JavaScript reads it
const userCountry = document.body.dataset.userCountry || 'US';
Conditional Script Loading by Country
Basic Country-Based Loading
Load different scripts based on detected country:
async function loadGeographicScripts() {
const country = await getUserCountry();
// EU countries - load GDPR compliance script
const euCountries = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'];
if (euCountries.includes(country)) {
JavaScriptActivator.load({
script: 'https://example.com/gdpr-compliance.js',
condition: () => true
});
}
// US - California - load CCPA script
if (country === 'US') {
// You might need additional state detection for CCPA
JavaScriptActivator.load({
script: 'https://example.com/ccpa-compliance.js',
condition: () => true
});
}
// UK-specific features
if (country === 'GB') {
JavaScriptActivator.load({
script: 'https://example.com/uk-features.js',
condition: () => true
});
}
}
Region-Based Loading
Group countries into regions for easier management:
function getRegion(country) {
const regions = {
'EU': ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'],
'NA': ['US', 'CA', 'MX'],
'APAC': ['AU', 'NZ', 'JP', 'KR', 'CN', 'IN', 'SG'],
'LATAM': ['BR', 'AR', 'CL', 'CO', 'PE'],
};
for (const [region, countries] of Object.entries(regions)) {
if (countries.includes(country)) {
return region;
}
}
return 'OTHER';
}
async function loadRegionalScripts() {
const country = await getUserCountry();
const region = getRegion(country);
switch(region) {
case 'EU':
JavaScriptActivator.load({ script: 'eu-region.js' });
break;
case 'NA':
JavaScriptActivator.load({ script: 'na-region.js' });
break;
case 'APAC':
JavaScriptActivator.load({ script: 'apac-region.js' });
break;
default:
JavaScriptActivator.load({ script: 'default-region.js' });
}
}
Compliance Scripts
GDPR Compliance (EU)
Load GDPR compliance scripts for European users:
async function loadGDPRCompliance() {
const country = await getUserCountry();
const euCountries = ['AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'];
if (euCountries.includes(country)) {
JavaScriptActivator.load({
script: 'https://cdn.example.com/gdpr-consent.js',
condition: () => true,
onLoad: () => {
// Initialize GDPR consent manager
if (typeof GDPRConsent !== 'undefined') {
GDPRConsent.init();
}
}
});
}
}
Performance Optimization
CDN Selection by Region
Load scripts from the nearest CDN location:
function getCDNUrl(country) {
const cdnMap = {
'US': 'https://cdn-us.example.com/script.js',
'GB': 'https://cdn-eu.example.com/script.js',
'DE': 'https://cdn-eu.example.com/script.js',
'JP': 'https://cdn-asia.example.com/script.js',
'AU': 'https://cdn-asia.example.com/script.js',
};
return cdnMap[country] || 'https://cdn-default.example.com/script.js';
}
async function loadOptimizedScript() {
const country = await getUserCountry();
const cdnUrl = getCDNUrl(country);
JavaScriptActivator.load({
script: cdnUrl,
condition: () => true
});
}
Caching User Location
Cache location to avoid repeated API calls:
async function getCachedUserCountry() {
// Check cache first
const cached = sessionStorage.getItem('user_country');
if (cached) {
return cached;
}
// Fetch if not cached
const country = await getUserCountry();
sessionStorage.setItem('user_country', country);
return country;
}
Fallback Handling
Always provide fallbacks for when location detection fails:
async function loadScriptsWithFallback() {
let country;
try {
country = await getUserCountry();
} catch (error) {
console.warn('Geolocation failed, using default');
country = 'US'; // Default fallback
}
// Load scripts based on detected or default country
if (country === 'EU_REGION') {
JavaScriptActivator.load({ script: 'eu-script.js' });
} else {
JavaScriptActivator.load({ script: 'default-script.js' });
}
}
Best Practices
- Privacy Compliance: Only detect location if necessary and with user consent where required
- Performance: Cache location data to avoid repeated API calls
- Fallbacks: Always provide default behavior when location detection fails
- Accuracy: Use appropriate detection method (IP for country, timezone for timezone-based features)
- User Control: Allow users to override location-based features when appropriate
- Documentation: Document which countries/regions trigger which scripts
Common Use Cases
- GDPR Cookie Consent: Load consent manager only for EU users
- Regional Payment Methods: Load payment integrations based on country
- Language Selectors: Load language switcher for multilingual regions
- Currency Converters: Load currency features for international users
- Shipping Calculators: Load region-specific shipping calculation scripts
- Tax Calculators: Load tax calculation scripts based on location
Conclusion
Geographic-based script loading enables personalized experiences and ensures compliance with regional regulations. By using JavaScript Activator with geolocation detection, you can conditionally load scripts based on user location while maintaining good performance and user experience. Always implement proper fallbacks and respect user privacy when implementing location-based features.
Leave a Reply