| 1 |
// Performance optimized: Run immediately without waiting for DOMContentLoaded |
| 2 |
// Only execute for bot traffic to minimize performance impact on real users |
| 3 |
(function () { |
| 4 |
'use strict'; |
| 5 |
|
| 6 |
// Early exit if no OTTO data configured |
| 7 |
if (!window.saOttoData) { |
| 8 |
return; |
| 9 |
} |
| 10 |
|
| 11 |
// Early exit if not a bot - saves execution time for real users |
| 12 |
const saDyoUseragent = navigator.userAgent; |
| 13 |
const isBot = /bot|crawl|spider|slurp|mediapartners/i.test(saDyoUseragent); |
| 14 |
|
| 15 |
if (!isBot) { |
| 16 |
return; // Skip execution for non-bot traffic to improve performance |
| 17 |
} |
| 18 |
|
| 19 |
const { page_url, otto_uuid, context } = window.saOttoData; |
| 20 |
const postPageCrawlLogs = async (pageUrl, uuid, context) => { |
| 21 |
try { |
| 22 |
if (isBot) { |
| 23 |
const saDyoApiUrl = 'https://sa.searchatlas.com/api/v2/otto-page-crawl-logs/'; |
| 24 |
const saDyoBodyData = { |
| 25 |
otto_uuid: uuid, |
| 26 |
url: pageUrl, |
| 27 |
user_agent: saDyoUseragent, |
| 28 |
context: context |
| 29 |
}; |
| 30 |
|
| 31 |
try { |
| 32 |
const saDyoResources = performance.getEntriesByType('resource'); |
| 33 |
const saDyoTotalResponseTime = saDyoResources.reduce((sum, r) => sum + (r.responseEnd - r.startTime), 0); |
| 34 |
const saDyoAverageResponseTime = (saDyoResources.length > 0) |
| 35 |
? (saDyoTotalResponseTime / saDyoResources.length).toFixed(2) |
| 36 |
: null; |
| 37 |
const saDyoTotalDownloadSize = saDyoResources.reduce((sum, r) => sum + (r.transferSize || 0), 0); |
| 38 |
const saDyoTotalDownloadSizeKB = (saDyoTotalDownloadSize / 1024).toFixed(2); |
| 39 |
|
| 40 |
if (saDyoAverageResponseTime) { |
| 41 |
saDyoBodyData.average_response_time = saDyoAverageResponseTime; |
| 42 |
} |
| 43 |
if (saDyoTotalDownloadSizeKB) { |
| 44 |
saDyoBodyData.total_download_size_kb = saDyoTotalDownloadSizeKB; |
| 45 |
} |
| 46 |
} catch (error) { |
| 47 |
|
| 48 |
} |
| 49 |
|
| 50 |
const saDyoResponse = await fetch(saDyoApiUrl, { |
| 51 |
method: 'POST', |
| 52 |
headers: { |
| 53 |
'Content-Type': 'application/json' |
| 54 |
}, |
| 55 |
body: JSON.stringify(saDyoBodyData) |
| 56 |
}); |
| 57 |
|
| 58 |
if (!saDyoResponse.ok) { |
| 59 |
return; |
| 60 |
} |
| 61 |
} |
| 62 |
} catch (error) { |
| 63 |
|
| 64 |
} |
| 65 |
}; |
| 66 |
|
| 67 |
// Use requestIdleCallback for better performance if available |
| 68 |
// Falls back to setTimeout for browsers that don't support it |
| 69 |
if ('requestIdleCallback' in window) { |
| 70 |
requestIdleCallback(() => { |
| 71 |
postPageCrawlLogs(page_url, otto_uuid, context); |
| 72 |
}, { timeout: 2000 }); |
| 73 |
} else { |
| 74 |
setTimeout(() => { |
| 75 |
postPageCrawlLogs(page_url, otto_uuid, context); |
| 76 |
}, 100); |
| 77 |
} |
| 78 |
})(); |
| 79 |
|