1

I have a usecase where i need to load and execute different js file in my html file depending upon the browser type.

If browser is safari i need to load <script type="text/javascript" src="./javascripts/applepay.js"> and if browser is any other i need to load two js files<script type="text/javascript" src="./javascripts/googlepay.js"></script> and <script async src="https://pay.google.com/gp/p/js/pay.js" onload="onGooglePayLoaded()"></script> .

Could you please let me know how can this be done?I tried a couple of solutions mentioned in other posts but it didnt work for me. Any code snippets will be very helpful.

vignesh d
  • 235
  • 3
  • 6
  • 15
  • To determine the browser, you'll want to rely on the user agent string value. I assume you already know how to load the javascript file, so I won't address that. Regarding the actual decisioning part, you'll want to load a main javascript file that will load, regardless of the user agent. In that file, you would then detect the user agent and load the corresponding javascript file. – David Tran Jan 25 '20 at 00:49

2 Answers2

3

I assume this is happening while the main HTML is loading. You can then use document.write() to insert the HTML for the appropriate script.

<script>
if (is_safari()) {
    document.write('<script type="text/javascript" src="./javascripts/applepay.js"></' + 'script>');
} else {
    document.write('<script type="text/javascript" src="./javascripts/googlepay.js"><' + '/script>');
    document.write('<script async src="https://pay.google.com/gp/p/js/pay.js" onload="onGooglePayLoaded()"><' + '/script>');
}
</script>

See Detect Safari browser for a number of ways to implement the is_safari() function.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You can create regexp to determine browser with window.navigator.vendor as below

if (window.navigator.vendor.match(/[Aa]+pple/g).length) {
  document.write("<script type='text/javascript' src='./javascripts/applepay.js'>")
} else {
  document.write("<script type='text/javascript' src='./javascripts/googlepay.js'></script><script async src='https://pay.google.com/gp/p/js/pay.js' onload='onGooglePayLoaded()'></script>")
}
Ahmet Zeybek
  • 1,196
  • 1
  • 13
  • 24