To load a third-party JavaScript file only if the visitor is not a bot, you can use the following approach -
// List of bot user-agent substrings
const botUserAgents = [
'Googlebot',
'Bingbot',
'Slurp', // Yahoo
'DuckDuckBot',
'Baiduspider',
'YandexBot',
'Sogou',
'Exabot',
'facebot', // Facebook
'ia_archiver'
];
// Function to check if the user-agent matches a bot
function isBot() {
const userAgent = navigator.userAgent;
return botUserAgents.some(bot => userAgent.includes(bot));
}
// Load third-party script if not a bot
if (!isBot()) {
const dyscript = document.createElement('script');
dyscript.src = 'https://example.com/thirdparty.js';
dyscript.async = true;
document.head.appendChild(dyscript);
console.log('Third-party script added because this is not a bot.');
} else {
console.log('Third-party script not added because this is a bot.');
}