简体   繁体   中英

How to load and run a javascript file conditionally

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM