0

I am having some trouble loading some javascript onto a page. It works when I embed the script directly into the page, but when I use ajax/jquery/getScript, it doesn't load. I think it might have something to do with async/sync or maybe some kind of cross domain restrictions.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script>

$.ajax({
    url: 'http://mobile.adnxs.com/ttj?id=1573223',
    crossDomain: true,
    dataType: "script",
    success: function () {
        // script is loaded
    },
    error: function () {
        // handle errors
    }
});

</script>
  • Cross-domain could very well have something to do with it. By default, AJAX going across domains is blocked (but not a direct – Katana314 Jul 19 '13 at 22:42
  • check this, http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain – Maverick Jul 19 '13 at 22:45
  • Could you use: http://api.jquery.com/jQuery.getScript/ ? – Jason Sperske Jul 19 '13 at 22:46
  • I'm not receiving any warnings, and I'm able to see the script load on the page. It just does nothing. – Nicholas Mitchell Jul 19 '13 at 22:46
  • I've tried getScript, but it's the same result. – Nicholas Mitchell Jul 19 '13 at 23:00
  • After looking at this again, I realized that the script source link is likely a PHP file that builds a the lines of JS. Any thoughts on how I could use JS to load the PHP so that it runs similarly to direct – Nicholas Mitchell Jul 22 '13 at 16:36

1 Answers1

0

You could inject the script tag dynamically:

$(document).ready(function() {
    var scriptTag = document.createElement('script');
    scriptTag.src = 'http://mobile.adnxs.com/ttj?id=1573223';
    scriptTag.onload = function() { /* script is loaded */ };
    scriptTag.onerror = function() { /* danger zone! * };
    $('head').append(scriptTag);
});

This works cross-domain, too.

Evan Hahn
  • 12,147
  • 9
  • 41
  • 59
  • Thanks Evan, I tried this; the script loads, but I'm not getting any output on the page. – Nicholas Mitchell Jul 19 '13 at 22:58
  • @NicholasMitchell Is it supposed to give an output? – Evan Hahn Jul 24 '13 at 19:27
  • Evan, yes there should be an output on the page. I've determined that the link is actually to php or something server side which echoes the javascript. So far, I've only been able to get an output by using document.write(). This is not an ideal solution, though. – Nicholas Mitchell Jul 29 '13 at 18:27