簡體   English   中英

如何有條件地加載和運行 javascript 文件

[英]How to load and run a javascript file conditionally

我有一個用例,我需要根據瀏覽器類型在我的 html 文件中加載和執行不同的 js 文件。

如果瀏覽器是 safari,我需要加載<script type="text/javascript" src="./javascripts/applepay.js">如果瀏覽器是其他瀏覽器,我需要加載兩個 js 文件<script type="text/javascript" src="./javascripts/googlepay.js"></script><script async src="https://pay.google.com/gp/p/js/pay.js" onload="onGooglePayLoaded()"></script>

你能告訴我怎么做嗎?我嘗試了其他帖子中提到的幾個解決方案,但對我不起作用。 任何代碼片段都會非常有幫助。

我假設這是在加載主 HTML 時發生的。 然后,您可以使用document.write()為適當的腳本插入 HTML。

<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>

有關實現is_safari()函數的多種方法,請參閱檢測 Safari 瀏覽器

您可以使用window.navigator.vendor創建正則表達式來確定瀏覽器,如下所示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM