使用远程src注入脚本标记并等待它执行 [英] inject a script tag with remote src and wait for it to execute

查看:86
本文介绍了使用远程src注入脚本标记并等待它执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将< script src =https://remote.com/>< / script> 元素注入我的页面,等待它要执行,然后使用它定义的函数吗?

How can I inject a <script src="https://remote.com/"></script> element into my page, wait for it to execute, and then use functions that it defines?

FYI:在我的情况下,脚本会在极少数情况下进行一些信用卡处理,所以我不这样做想要永远包括它。我希望在用户打开更改信用卡选项对话框时快速包含它,然后向其发送新的信用卡选项。

FYI: In my case, the script will do some credit card processing in rare cases, so I don't want to include it always. I want to include it quickly when the user opens up a change-credit-card-options dialog, and then send it the new credit card options.

编辑其他详细信息:我无法访问远程脚本。

Edit for additional detail: I do not have access to the remote script.

推荐答案

您可以使用 Google Analytics Facebook 的方法:

(function(d, script) {
    script = d.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.onload = function(){
        // remote script has loaded
    };
    script.src = 'http://www.google-analytics.com/ga.js';
    d.getElementsByTagName('head')[0].appendChild(script);
}(document));






更新:

以下是新的Facebook方法;它依赖于现有的脚本标记,而不是< head>

Below is the new Facebook method; it relies on an existing script tag instead of <head>:

(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)){ return; }
    js = d.createElement(s); js.id = id;
    js.onload = function(){
        // remote script has loaded
    };
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));




  • 替换 facebook-jssdk 使用您的唯一脚本标识符,以避免多次附加。

  • 将脚本的url替换为您自己的。

    • Replace facebook-jssdk with your unique script identifier to avoid it being appended more than once.
    • Replace the script's url with your own.
    • 这篇关于使用远程src注入脚本标记并等待它执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆