-1

I have a script that I have no control over and is on another domain. The default procedure is to just include it in a script tag and it runs fine.

I don't want to run it by default so I have an if statement and if true I want to run the script. So default option is:

<script src="http://domain/site/script?Id=12345&delayMs=2000&stayMs=10000&chance=0.1" type="text/javascript" ></script> 

I taught I could just use jQuery.getScript() to get it to run the above url but this does not work. I do not know the correct link to the actual script and functions contained so I cannot getScript and call functions.

Any ideas would help.

Regards Brian

4

1 回答 1

0

由于您遇到跨域问题,请试试这个($.getScript()无论如何只是这个的简写,除了crossDomain: true)。

$.ajax({
    url: 'http://domain/site/script?Id=12345&delayMs=2000&
                                    stayMs=10000&chance=0.1',
    crossDomain: true,
    dataType: 'script',
    success: function () {
        // script is loaded
    },
    error: function () {
        // handle errors
    }
});

您可以尝试使用纯 JS 的另一种解决方案:

function loadScript(src, callback)
{
  var s,
      r,
      t;
  r = false;
  s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = src;
  s.onload = s.onreadystatechange = function() {
    //console.log( this.readyState ); 
    //uncomment this line to see which ready states are called.
    if ( !r && (!this.readyState || this.readyState == 'complete') )
    {
      r = true;
      callback();
    }
  };
  t = document.getElementsByTagName('script')[0];
  t.parent.insertBefore(s, t);
}

用法:

var url = 'http://domain/site/script?Id=12345&delayMs=2000&
                                    stayMs=10000&chance=0.1';
loadScript(url, function(){
    console.log('script loaded');
});
于 2013-10-31T11:42:49.833 回答