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.

1
  • 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. Commented Jan 25, 2020 at 0:49

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.