Skip to content Skip to sidebar Skip to footer

Loading .js File Cross Domain Using Ajax

I'm trying to access a cross domain .js file using ajax: $.ajax({ type:'get', crossDomain:true, url: 'http://localhost/62588/scripts/bootStrapper.js', contentType:

Solution 1:

Don't use any AJAX, simply use the $.getScript function:

$.getScript('http://localhost/62588/scripts/bootStrapper.js').done(callback);

As you know, you could be pointing the <script> tag to any domain you wish without violating the same origin policy. That's the basis of JSONP. But you don't need any JSONP, because all you need is to reference a script form a remote domain, which is as simple as pointing the <script> tag to this script or if you want to do it dynamically use the $.getScript function that jQuery has to offer you.


UPDATE:

The $.getScript function will append a random cache busting parameter to the url. If you want to get a cached version of your script you could define a custom cachedScript function as shown in the documentation:

jQuery.cachedScript = function(url, options) {
    options = $.extend(options || {}, {
        dataType: 'script',
        cache: true,
        url: url
    });
    return jQuery.ajax(options);
};

and then:

$.cachedScript('http://localhost/62588/scripts/bootStrapper.js').done(callback);

Post a Comment for "Loading .js File Cross Domain Using Ajax"