Riley Lark Riley Lark - 6 months ago 45
Javascript Question

inject a script tag with remote src and wait for it to execute

How can I inject a

<script src=""></script>
element into my page, wait for it to execute, and then use functions that it defines?

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.


You could easily use Google Analytics or Facebook's method.

(function(d, script) {
    script = d.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.onload = function(){
        // remote script has loaded
    script.src = '';


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); = id;
    js.onload = function(){
        // remote script has loaded
    js.src = "//";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
  • Replace facebook-jssdk with your unique script identifier to avoid it being appended more than once.
  • Replace the script's url with your own.