What is the most effective method for conditionally defining functions in modern browsers?
I have noticed that Safari 12 (iOS 12.0.1 and macOS 10.14) does not correctly define conditional functions, while Chrome, Firefox, and Edge behave correctly. I am curious about the standard behavior for a JavaScript engine so that I can report this potential bug to Apple if necessary.
Context: We are implementing this approach to prevent Google Analytics (gtag.js) from loading unless a user consents to GDPR. The initialization code for Google's gtags.js contains a line
function gtag(){dataLayer.push(arguments);}
which causes issues in Safari.
Below is the code snippet, with a demo available at JS Fiddle
<html>
<head>
<title>Safari JS Engine Test</title>
<script type="text/javascript">
if (false) {
function conditionalFunctionality() {
alert("Performing conditional functionality");
}
}
window.onload = function() {
if (typeof conditionalFunctionality === "function") {
alert("BAD. It's defined");
} else {
alert("GOOD. It's NOT defined");
}
}
</script>
</head>
<body>
<h1>Safari JS Engine Test</h1>
</body>
</html>
Mugshots
https://i.sstatic.net/Y87Tfl.jpg https://i.sstatic.net/UdEIUl.png